Java puzzle 16: Conditional statements within a loop

  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

  1. 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.
  2. 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.
  3. When i is equal to 1 and 2, y is written to the standard output see the explanation of the step 2.
  4. When i is equal to 3 the statement if(i > 2) returns true. Therefore x is written to the standard output.
  5. The correct answer is that this program writes yyyx to the standard output.





Sar Maroof is a professional software development teacher, gives master classes and publishes technical articles. He is also an expert software developer and worked for several big as well as small companies and later as a freelancer.

 Subscribe to Sar Maroof's RSS feeds!
 Mail this page to a friend!
 Bookmark this page!

Leave a Reply

Your email address will not be published. Required fields are marked *