Develop a C++ program that determines the largest and second largest positive values in a collection of data
Prompt the user to enter integer values until they enter any negative value to quit
Create a loop structure of some sort to execute this input cycle
Maintain the largest and second largest integer as the user inputs data
Display the largest and second largest values entered by the user
[C++ CODE]
#include<iostream>
#include<stdio.h>
using namespace std;
int main()
{
int i, high, high_2, count=0, num; //high is the largest value and high_2 is the second largest
cout<<"Enter the integers value and enter -ve value to quit : "<<endl;
do{
cin>>num;
count++;
if(count==1) //if first integer, high and second highest will be same
{
high = num;
high_2 = num;
}
else if(num < 0) // if num is negative it will break out
{
break;
}
else if(num>high)
{
high_2 = high;
high = num;
}
else if(num>high_2)
{
high_2=num;
}
}while(num > 0);
cout<<endl<<"Largest value is "<<high<<endl<<"Second largest value is "<<high_2;
return 0;
}
SCREENSHOT:
OUTPUT:
EXPLANATION:
Two integer variables high and high_2 are taken to store the largest and second-largest values.
Integer value taken by the user is stored in num variable.
the count is the number of integers taken by the user.
At first, when count=1, then high and high_2 are assigned by num value and in second input it is checked if it is greater than high then high is shifted to high_2 and num is shifted to high.
If num is greater than high_2 and less than high than num value is shifted to high_2.
And this process continues till the end of the loop.
Get Answers For Free
Most questions answered within 1 hours.