Learning_Java Learning_Java - 2 months ago 29
Java Question

For loop counter

What will be the largest value printed by the following code?

for (int x=5; x > 0; x--) // I think that the loop counts down from 5 to 1 (subtracting 1 each time)
for (int y=0; y < 8; y++) // I think the loop counts up from 0 to 7 (adding 1 each time)

a. 5
b. 8
c. 35
d. 40
e. 64

In my head i pictured this for the loop:


The loop stops at 1 for the first for loop because 1 is the lowest it goes. The second for loop stops because the first one stopped. For the answer choices, I chose 5 because what I pictured in my head, 5 turned out to be the largest number. The real answer to this problem is "C. 35". Does anyone know how to get this answer? I also may be wrong with my understanding of this particular loop. Thank you in advance.


OKay, You are getting very confused here. This is an example of Nested Loops.

The second loop will execute 5 times. So the output will be like -

For x=5 5*1 5*2 5*3 .. and So on

For x=4 4*1 4*2 .. and So on.. Likewise for Other values of x.

Please Read nested loops. That's Basic Programming