Thursday, 20 February 2014

Largest of n Numbers - C++ Program Sourcecode!

Our aim in this program is to accept any number of numbers from the user, and to display the largest from it. Let's jump into the sourcecode:

Code:
#include<iostream.h>
void main()
{
    int number[10], large, i,n;
    cout<<"Enter the number of numbers : ";
    cin>>n;
    for(i=0;i<n;i++)
    {
       cout<<"\nEnter number "<<i+1<<" : ";
       cin>>number[i];
    }
    large = number[1];
    for(i=0;i<n;i++)
    {
        if(large<=number[i])
        {
            large = number[i];
        }
    }
    cout<<"\nLargest number is "<<large<<endl<<endl;
}

For newer IDEs, visit this page.
Working:

First, we simply ask the user to specify the number of numbers, and input an array with all the numbers. Next step is processing the array. Consider the numbers to be 10,12,11,5, and 15.

Processing ~

STEP 1 : We let the variable large equal to the first element of the array. Hence in this case,  large = first element (i.e., number[0]) = 10.

STEP 2 : We open a for loop, with limits 0 and n (in this case n is 5). If large is less than or equal to number[i], the variable large is reset to number[i]. In this case, number[2] is less than number[1] (since 10 < 12), so the value of large is changed from 10 to 12.

This process continues n times so that all the elements are compared to large.

On the next run,value of large remains 12, since 12 is not less than 11.
Similarly, on the next run also, large remains 12, since 12 is not less than 5.
On the next run, value of large is reset to 15, since 12 is less than 15.
 Thus the loop is terminated and final value of large is set to 15.

Now we output the variable large, which will be set to the largest number in the array.

Output:


Of course, there are many other methods to do this program, but I chose this method to show you a simple array manipulation technique in C++. You may use your intuition to solve this problem in any other way!

Happy Coding!!!

1 comment:

You might also like