C++/loop
Expert: vijayan - 4/20/2009
QuestionI was the following...
Write a program that displays a menu with the following choices to the user.
A - Find the largest # with a known quantity of numbers
B - Find the smallest # with an unknown quantity of numbers
C - Quit
Please enter your choice ___
This menu needs to be repeatedly displayed until the user chooses to quit.
If A is chosen, you should ask the user how many numbers he wants to enter. If he enters 5, you should read 5 numbers from him. You should then display the largest number he entered. Use a for loop to read these and display the largest.
If B is chosen, you should keep reading numbers no matter what until the user enters -99. Then you should display the smallest number he entered not counting the -99.
can you help me get started?
Answerrevision: change to public
to find the largest number entered by a user, you do not need to store all the numbers in memory. this would do:
a. initially make the first number entered by the user the largest number.
int largest_so_far ;
std::cin >> largest_so_far ;
b. read the remaining numbers in a loop and check against the largest so far read.
begin loop:
int number ;
std::cin >> number ;
if( largest_so_far < number ) largest_so_far = number ;
end loop
the only difference between options A and B is the kind of loop you would write.
A:
int N ; // how many numbers
std::cin >> N ;
int largest_so_far ;
std::cin >> largest_so_far ; // read first number
for( int i=1 ; i<N ; ++i ) // read remaining N-1 numbers
{
// ...
}
B:
int largest_so_far ;
std::cin >> largest_so_far ; // read first number
int number ;
while( ( std::cin >> number ) && ( number != -99 ) )
{
// ...
}