Friday, 25 October 2013

Finding largest two numbers from N numbers

Finding largest two numbers from N numbers:


 This C program example finds the two largest numbers from the list of 'N' numbers.

Mechanism:
In this program, we have declared the variable of:
  • Size
  • Input
  • First largest
  • Second largest
 First, we take input of size and then we enter a for loop which executes for 'size' times. This program is designed in such a way that it checks all negative and positive integers. This program uses an if else and else if structure and for loop structure structure to execute the logic of the program. This program also works on boundary lines. Time complexity of this program is O(size). Once the loop terminates, it prints the first largest and second largest value from the N numbers.

Code:

/*              Join us at
http://shapesinc.blogspot.com 
for more codes of shapes                            
*/
#include<iostream>
using namespace std;
int main()
{
cout << "Join http://shapesinc.blogspot.com for more codes of shapes\n\n";
cout<<"CAUTION:   The input should not be other than numerical values \n\n\a";
int i, num, largest = 0, seclargest = 0, size; cout << "Enter the amount of numbers you want to enter\n"; cin>>size; if (size<=0) { cout << "No values entered\n"; goto finish; } cout << "Please enter the numbers from the keyboard.\n" << endl; for (int i=0; i<size; i++ ) { cin >> num; if(i==0) largest=num; else if(i==1) { if(num>largest) { seclargest = largest; largest = num; } else seclargest=num; } else if ( num > largest ) { seclargest = largest; largest = num; } else if ( num > seclargest ) seclargest = num; } cout << "\nThe largest of the numbers entered is " << largest << endl ; cout << "\nThe second largest of the numbers entered is " << seclargest << endl ; finish: return 0; }

Final Words:
By this post, you can learn C online practically. We have tried our best to make this program understandable and optimized.

3 comments:

  1. You are doing great work.
    But I have a small problem,can you solve it.
    How to set time for reading an input, if user fails to enter a value within time then a message appears "time up" or if user enters a value within time then then program proceed?
    I there is any function???
    Well I'm using Visual Studio 2013 Ultimate
    thank You

    Well you are doing great work
    Appreciate your work
    Keep Posting
    thank You

    ReplyDelete
    Replies
    1. Well brother, I have don't have such function in mind yet. I'll look for it. However there is a function Sleep(int) which can produce a delay. int value is passed and you have to include #include for it.
      e.g: Sleep(1000) will produce a delay of 1 second. remember S in sleep is capital. :)

      Delete
  2. Its wonderful blog really very nice site and blog facility.every title is very nice and very fatastic concept.Private Tutor Naples Thanks for sharing the information.

    ReplyDelete