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 |
> |
---|

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; } } }

## Suggested Articles

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