Category: Java puzzles

Java puzzle 01: A simple loop

Choose a Puzzle:    Green = Easy,   Blue = Normal,   Red = Hard
P01  |   P02  |   P03  |   P04  |   P05  |   P06  |   P07  |   P08  |   P09  |   P10  |   P11  |   P12  |  

If this simple program is compiled and run, the following is written to the standard output.
-x1-x2-x3-x4-x5-x6-x7-x8-x9-x10

Add only one statement to the line 8. As a result of that the program writes “-x1-x7” to the standard output.

Java puzzle 1: A simple loop

Level: Normal

public class MyClass
{
  public static void main(String[] args)
  {
    for (int x = 1; x <= 10; x++)
    {
      System.out.print("-x" + x);
      // add a statement here!
    }
  }
}

Author: Sar Maroof

Answer explanation

The loop of this program starts from the initial value of x = 1.
each time the loop repeats, x++ increments the value of x by one until the value of x is equal to 9 or the conditional x<=10 returns false.

We add the statement x += 5 on line 8.
When the first time the loop is executed the statement System.out.print(“-x” + x); writes -x1
to the standard output. That is because the initial value of x is one.
The statement x += 5; increments the value of x by 5, then x++ increments the value of x by one.

By the second execution of the loop, the value of x is equal to 7. The statement
System.out.print(“-x” + x); writes -x7 to the standard output.

The statement x +=5 increments the value of x by 5. Therefore the value of x becomes 12 and that is greater than 10. The conditional x <=10 returns false. Therefore the loop is terminated.
The program writes: -x1-x7 to the standard output.

The answer is: x+=5;

public class MyClass
{
  public static void main(String[] args)
  {
    for (int x = 1; x <= 10; x++)
    {
      System.out.print("-x" + x);
      x+=5;
    }
  }
}

 


If you have difficulties to understand this question and the explanation, I think that you need to read my book first. It contains 17 chapters of standard Java. Click on the link for more information about the English version of the book Java quizmaster for beginners

Please, leave your questions, feedback and suggestions in the comments below!
Sarmaroof.com offers a practical method to learn and improve your Java skills. It avoids unnecessary long boring theoretical explanations, but it uses many exercises and quizzes.



Sar Maroof's new book
Java quizmaster for beginners (English)

Java quizmaster voor beginners (Dutch)
Sar Maroof is the author of two Java books namely, Java quizmaster for beginners and A guide to build a Java application.
Experience with developing web applications since 2001
Sun Certified JSP as well as EJB
CIW Certified Internet Webmaster
Applied Science in Physics HBO Amsterdam
As well as Bachellor Science in Physics.

 Subscribe To sarmaroof RSS Feeds! (Your Browser)
 Mail This Page To A Friend!
 Bookmark This Page!

Sarmaroof © 2017