<< |
Java Puzzles Green = Easy, Blue = Normal, Red = Hard P01 P02 P03 P04 P05 P06 P07 P08 P09 P10 P11 P12 P13 P14 P15 P16 P17 P18 P19 P20 P21 P22 P23 P24 By title |
>> |
---|

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 1.
- 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 found this difficult, you might consider reading my book Java quizmaster for beginners. It is easy to understand, organized to learn Java in 17 days and it guides you to master Java code by solving 105 quizzes and 117 assignments. This book explains each chapter properly before starting with exercises and assignments. It is available on Amazon. See inside the book here!

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.

## Suggested Articles

## Books by Sar Maroof |

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