Largest & Second Largest In Array


Program to find the Largest and Second Largest in list(array) entered by user in C++






#include<iostream.h>
#include<conio.h>

void main()
{
          int a[20],i,j,n,lar=-32000,slar=-32000;
          clrscr();
          cout<<"\nEnter total no. of elements :: ";
          cin>>n;
          for(i=0;i<n;i++)
          {
                    cout<<"\nEnter Element :: ";
                    cin>>a[i];
          }
          for(i=0;i<n;i++)       // loop to find largest.
                    if(a[i]>lar)
                    {
                              lar=a[i];
                              j=i;                  // restore location of largest.
                    }
          for(i=0;i<n;i++)      // loop to find second largest.
                    if(a[i]>slar && i!=j) // exclude largest to find second largest.
                              slar=a[i];
          cout<<"\nLargest is "<<lar<<"\nSecond Largest is "<<slar;
          getch();
}

OUTPUT

Enter total no. of elements:: 4
Enter Element:: 4
Enter Element:: 2
Enter Element:: 3
Enter Element:: 3

Largest is 4
Second Largest is 3


-----

Firoz Memon

Please view my other blogs:

          C++ Codes 4 Beginners

          Java Tips

          Java 4 Beginners

Previous Post Next Post