Quizzes Assignments Puzzles Easy exercises Required knowledge |
< |
Java Quizzes Green = Easy, Blue = Normal, Red = Hard Select 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 By title |
> |
---|
For many of the projects on which I worked, I needed to use loops within loops. In the beginning seems very hard, but if you understand the process you become gradually familiar with it.
Java quiz 15: Loop within loop
Level: Hard
What is the output of this code?
public class MyLoop { public static void main(String[] args) { int y = 0; while(y < 14) { y++; for(int i = 1; i < 4; i++) { y += i; } } System.out.println(y); } }
Author: Sar Maroof
Answer explanation
- If y is smaller than 14 the body of the while loop is executed. The initial value of y is 0.
- When the body of the while loop is excuted the statement y++; increments the value of y by 1. y = 0 + 1 = 1.
- The second loop is a for loop. The initial value of i is 1 and the body of the loop is executed as long as y is smaller than 4. This loop is executed for the values of i 1, 2, 3. The statement y += i increments the value of y by i. So, y = 1 + 1 + 2 + 3 = 7.
- The last value of y is 7 and that is smaller than 14. The body of the while loop is executed for the second time and y ++; increments the value of y by 1, y = 7 + 1 = 8.
- The body of the for loop is executed and the statement y += i increments the value of y by i and those are 1, 2, 3. So, y = 8 + 1 + 2 + 3 = 14. The while loop is terminated because y is no longer smaller than 14.
The correct answer is: b.
Suggested Articles
![]() ![]() ![]() |