Create a program that will do the following:
- Ask the user for a number from 1 to 20, check to ensure that a valid number is entered
- Ask the user for a second number from 1 to 20, check to ensure that a valid number is entered
- Ask the user for a third number from 1 to 20, check to ensure that a valid number is entered
- Display a message telling the user what is the largest number
- Display a message telling the user what is the second largest number
#include<iostream>
using namespace std;
int main(){
int first;
cout<<"Enter the first number\n";
cin>>first;
while(first<1 || first >20){
cout<<"Invalid number\n ";
cout<<"Enter the first number\n";
cin>>first;
}
int second;
cout<<"Enter the second number\n";
cin>>second;
while(second<1 || second >20){
cout<<"Invalid number\n ";
cout<<"Enter the second number\n";
cin>>second;
}
int third;
cout<<"Enter the third number\n";
cin>>third;
while(third<1 || third >20){
cout<<"Invalid number\n ";
cout<<"Enter the third number\n";
cin>>third;
}
int arr[3] = {first, second,third};
int max = arr[0];
int min = arr[0];
for(int i = 0 ; i<3; i++){
if(arr[i]>max){
max = arr[i];
}
}
int second_largest = 0;
for(int i = 0 ; i<3; i++){
if(arr[i]<min){
min = arr[i];
}
}
for(int i = 0 ; i<3; i++){
if(arr[i] != max && arr[i] != min){
second_largest = arr[i];
}
}
cout<<"The largest element: "<<max<<"\nSecond largest element: "<<second_largest<<endl;
}
Comments
Leave a comment