Tuesday, December 9, 2014

C++ program for finding 1st maximum and 2nd maximum in a list of numbers

#include<iostream>
using namespace std;

int main()
{
const int NUMBERS=20;
int num[NUMBERS];
for(int i=0 ; i<NUMBERS ; i++ )
{
cout << "Enter number "
<< (i+1)
<< ": ";
cin >> num[i];
}
int high1,high2,index;
high1=num[0];
index=0;
for( int i=0 ; i<NUMBERS ; i++ )
{
if( num[i]>high1 )
{
high1=num[i];
index=i;
}
}

if( high1==num[0] )
{
for( int j=0 ; j<NUMBERS ; j++ )
{
if( high1!=num[j] )
{
index=j;
break;
}
}
high2=num[index];
for( int j=index ; j<NUMBERS ; j++ )
{
if( num[j]>high2 && num[j]<high1 )
high2=num[j];
}

}
else
{
high2=num[0];
for( int j=index ; j<NUMBERS ; j++ )
{
if( num[j]>high2 && num[j]<high1 )
high2=num[j];
}
}
if( high1!=high2 )
{
cout << "\nLargest number is: "
<< high1
<< endl;
cout << "And second is: "
<< high2
<< endl;
}
else
{
cout << "\nLarget number is: "
<< high1
<< "\nAll the numbers are equal so there is no second largest."
<< endl;
}

return 0;
}

No comments:

Post a Comment