Answer to Question #244561 in C++ for Ddg

Question #244561

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


1
Expert's answer
2021-09-29T18:44:13-0400
#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;
	
	
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS