Results 1 to 4 of 4
- 11-17-2010, 02:58 PM #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.)
My answer was 53, but that was wrong. Will someone explain to me why my answer was wrong & what is the right answer?Java Code:sum = console.nextInt(); num = console.nextInt(); while (num != -1) { num = console.nextInt(); sum = sum + num; } System.out.println(sum);
- 11-17-2010, 03:36 PM #2
Member
- Join Date
- Nov 2010
- Posts
- 12
- Rep Power
- 0
If I'm reading your question correctly, it's going like this:
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.
- 11-17-2010, 04:26 PM #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?
lalaJava Code:sum = console.nextInt(); num = console.nextInt();
- 11-17-2010, 04:39 PM #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
Similar Threads
-
Loop Help Please
By JavaAssistance in forum New To JavaReplies: 11Last Post: 09-26-2010, 10:05 PM -
How can I rewrite the following while loop using a for loop?
By gt11990 in forum New To JavaReplies: 5Last Post: 04-30-2010, 05:05 PM -
while-loop stopping on first loop
By davester in forum New To JavaReplies: 6Last Post: 06-26-2009, 08:46 PM -
For Loop
By kian_hong2000 in forum New To JavaReplies: 1Last Post: 08-07-2008, 02:01 PM -
while loop
By Unknown1369 in forum New To JavaReplies: 5Last Post: 07-08-2008, 10:15 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks