# Thread: Sentinel_Controlled while Loop (?)

1. Member
Join Date
Oct 2010
Posts
80
Rep Power
0

## Sentinel_Controlled while Loop (?)

Good Morning.
This is the question:
Suppose sum and num are int variables, and the input is:
15 18 20 -1

What is the output of the following code? (Assume that console is a Scanner object initialized to the standard input device.)
Java Code:
```sum = console.nextInt();
num = console.nextInt();

while (num != -1)
{
num = console.nextInt();
sum = sum + num;
}
System.out.println(sum);```
My answer was 53, but that was wrong. Will someone explain to me why my answer was wrong & what is the right answer?

2. Member
Join Date
Nov 2010
Posts
12
Rep Power
0

sum takes the value 15.
num takes the value 18.
the while loop checks to see if num is equal to -1, it's not, so the loop executes.
num now takes the value 20.
sum and num are added, to give you 20 + 15, which is 35.
num is again checked, and since it's now 20, the loop is executed again.
num now takes the value -1.
num is added to sum again, to give you 34.
then num is -1, so the loop is done, and sum should be printed as 34.

3. Member
Join Date
Oct 2010
Posts
80
Rep Power
0

## Sentinel_Controlled while Loop (?)

Thanks for responding lonegreyride.
34(??) I don't see how you got 34 (?)

1st time: Sum=15, NUM=18
while...
NUM=18,SUM=SUM+NUM=33

2nd Tme: Sum=33, NUM=20
SUM=33+NUM=20, AUM=53

Are you saying that these 2 statements are only
used once in the program, the beginning, with values of 15 and 18?
Java Code:
```sum = console.nextInt();
num = console.nextInt();```
lala

4. Member
Join Date
Nov 2010
Posts
12
Rep Power
0
Yes, exactly. num only holds the value 18 as it's checked before the first iteration of the loop. As soon as the loop starts, that value of 18 is replaced by 20, so the first two values that are added are 15 and 20, not 15 and 18.

So...
1st time: sum = 15, num = 18
enter the loop, num = 20
sum(15) + num(20) = 35

2nd time: sum = 35, num = 20
enter the loop, num = -1
sum(35) + num(-1) = 34

3rd time: sum = 34, num = -1
loop does not execute

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•