go to previous page   go to home page   go to next page hear noise

Answer:

Yes: each iteration of the loop will add a new number to the sum.


Adding up User-entered Integers

sentinel loop

 

The loop adds each integer the user enters to a sum. A counting loop could do this if the user first said how many integers were in the list. But often users don't know this in advance or would find it annoying to find out. (If you have a column of integers, you would like to enter them one by one until you reach the last one. It would be annoying if you were required to count them in advance.)

A sentinel controlled loopuses a special value (the sentinel) to say when the loop is done. In this example, the user enters a zero after the last integer to add. Zero is the sentinel. Here is how the program works:

C:\users\temp>java AddUpNumbers

Enter first integer (enter 0 to quit): 12
Enter an integer (or 0 to quit): -3
Enter an integer (or 0 to quit): 4
Enter an integer (or 0 to quit): 0
Sum of the integers: 13

The flowchart shows the idea. It looks much like the flowcharts for other loops, but now the conditional expression value!=0 tests for a sentinel value.


QUESTION 2:

Is there any limit to how many times the loop body could execute?