Java quiz 15: Loop within loop

  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

Select the correct answer.


Answer explanation

  1. If y is smaller than 14 the body of the while loop is executed. The initial value of y is 0.
  2. When the body of the while loop is excuted the statement y++; increments the value of y by 1. y = 0 + 1 = 1.
  3. 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.
  4. 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.
  5. 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.





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 *