I wrote a program to find the largest number. This program use a while statement to prompt the user to enter 10 numbers. Then we get the largest number.
What changes should I do if I want the program to find the two largest number of the ten numbers?
#include <iostream>
#include <string>
usingnamespace std;
int main(){
double counter{1};
double number{0};
double largest;
cout << "Please enter a number: ";
cin >> largest;
while(counter<10){
cout << "Please enter a number: ";
cin >> number;
if (number>largest){
largest = number;
}
counter += 1;
}
cout << "The largest number is: " <<
largest;
}
#include <iostream>
int main() {
double largest ;
std::cout << "Please enter a number: ";
std::cin >> largest ;
double second_largest ;
std::cout << "Please enter a second number: ";
std::cin >> second_largest ;
// make sure that largest is greater than second_largest
// by swapping them if largest is less than second_largest
if( largest < second_largest ) {
constdouble temp = largest ;
largest = second_largest ;
second_largest = temp ;
}
int counter = 2 ; // note: int
while( counter < 10 ) {
double number ;
std::cout << "please enter another number: " ;
std::cin >> number;
if( number > largest ) {
second_largest = largest ;
largest = number ;
}
elseif( number > second_largest ) second_largest = number ;
++counter ;
}
std::cout << "the largest number is " << largest << '\n'
<< "and the next largest number is " << second_largest << '\n' ;
}