Transcript Document
Chapter 4 Practice
Practice with ++, -- operator
1. What will be the output of the following
program segment:
1. x = 2;
y = x++;
System.out.println(y);
2. x = 2;
System.out.println(x++);
3. x = 8;
y = x--;
System.out.println(y);
Practice with ++, -- operator
2. What will be the output of the following
program segment:
1. x = 2;
y = 2*--x + x++;
System.out.println(y);
2. x = 2;
y = 2*++x + x--;
System.out.println(y);
Practice with while statement
1.
How many times will “Hello” be printed in the following program
segment?
int count = 10;
while (count < 1) {
System.out.println(“Hello”);
count++;
}
2.
How many times will “Hello” be printed in the following program
segment?
int count = 0;
while (count < 10) {
System.out.println(“Hello”);
}
3.
How many times will “Hello” be printed in the following program
segment?
int count = 0;
while (count < 10) {
System.out.println(“Hello”);
count++;
}
Practice with while/do-while
statement
4. Write an input validation loop that asks the user
to enter a number representing the age of a
teenager (in the range of 13 through 19).
5. Write an input validation loop that asks the user
to enter letter ‘Y’, ‘y’, ‘N’, or ‘n’.
6. Write an input validation loop that asks the user
to enter a string “Yes” or “No”.
7. Write an input validation loop that asks the user
to enter a number representing a leaf year.
8. Write an input validation loop that asks the user
to enter a string having the length of at least 6
characters.
Practice with for statement
1.
What will the following program segment display?
1.
2.
3.
2.
3.
4.
for (int c = 0; c < 6; c++)
System.out.println(c + c);
for (int c = -5; c < 5; c++)
System.out.println(c);
int c;
for (c = 5; c <=14 ; c+=3)
System.out.println(c);
System.out.println(c);
Write a for loop that displays your name 10 times.
Write a for loop that displays all numbers between 1 and
100, and ending with 0 or 5.
Write a for loop that displays all powers of 2 between a
and b, where a and b are natural numbers entered from
keyboard, a < b.