Quizzes Assignments Puzzles Easy exercises Required knowledge |
< |
Java Puzzles 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 |
> |
---|
Here is the puzzle of today, which demonstrates a conditional statement within a loop.
Java puzzle 16: Conditional statements within a loop
Level: Normal
What is the output of this program and why?
public class MyClass { public static void main(String[] args) { for(int i = 0; i < 4; i++) { if(i > 2) { System.out.print("x"); } else { System.out.print("y "); } } } }
Author: Sar Maroof
Answer explanation
- The loop is repeated 4 times, because the initial value of the variable i is 0 and the body of the loop is executed as long as i is smaller than 4.
- When i is equal to 0, the body of the loop is executed. The statement if(i > 2) returns false. Therefore the else block is executed and y is written to the standard ouput.
- When i is equal to 1 and 2, y is written to the standard output see the explanation of the step 2.
- When i is equal to 3 the statement if(i > 2) returns true. Therefore x is written to the standard output.
- The correct answer is that this program writes yyyx to the standard output.
Suggested Articles
![]() ![]() ![]() |