C++/C++ help

Advertisement


Question
For my assignment I am to write a program that reads a series of integers from the keyboard.  I am also required to use a sentinel number (a number that causes the loops to halt and display the results).  Once the user has entered a series of integers ranging from 1 to 100, the user will then enter a sentinel number to stop the loops.  The resulting output should show the average of the integers as well as the maximum and minimum integers.  

I know how to code a loop with a sentinel number that halts it, but I am unsure of how to make the program display the maximum and minimum integers in the user given numbers.  We have not learned arrays yet so I am now allowed to use them.  In my notes, I have written down that the teacher said to use climits int_min and int_max I think.  I am just unsure how to code these as my book does now show this.

Thanks

Answer
Hello John

You are correct that you need two integers to save the min and max.

Declare them like this:

int min_int;
int max_int;

You will also need a counter and a total, which you should initialize to 0. They are used to calculate the average.

int counter=0;
float total=0;

Make the total a floating point number. If you make it an integer, then both counter and total would  be integer and the division (total/counter) would be done with integer arithmetic, causing the fractional part to be chopped off.

Notice that min_int and max_int are not initialized to anything, so you cannot compare them against a number until they are initialized.

Inside the loop, when you get a valid number, check if counter is zero, and if it is zero, set min_int and max_int to the current number.

If counter is not zero, then check the current number against the max_int and reset the max_int if the current number is bigger. Like this:

if (current_number > max_int)
{
   max_int = current_number;
}

Use the same idea to reset the min_int.

Finally, at the end of your loop, print out the results. Don't forget to handle the case when the user puts in the sentinel as the first value.

Show me your work and I'll give you my comments.

Once your program is working, change total to an integer type and run the program again with the same numbers to see how the average changes. Don't forget to set it back to float before handing it in.

Best regards
Zlatko

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Zlatko

Expertise

No longer taking questions.

Experience

No longer taking questions.

Education/Credentials
No longer taking questions.

©2016 About.com. All rights reserved.