Exercise 4.7
- In the section on avoiding errors, we stated that the fragment
for (int i = 1; i < 100; i++);
System.out.println(i + " " + i*i);
would not print a table of squares of the integers from 1 to 100. What
would it print?
- What value(s) of the variable response will stop the following loops?
- while (response <= 'a' && response >= 'z' )...
- while (response >= 'A' II response <= 'E' )...
- What is wrong with the following fragment?
do
{
System.out.println("Enter transaction code");
char transCode = In.getChar();
System.out.println("Code entered: " + transCode
+ "\nls this correct? (Y/N)");
char response = In.getChar();
}
while (response != 'Y' I I response != 'N');
- Modify the fragment so that it behaves in a more appropriate
way.
- How many times will the following loop be executed? Justify your
answer.
int n = 40;
while (n > 0);
{
System.out.println(n);
n /= 2;
}
- Rewrite each loop to make it clearer.
-
for (int i = 1; i <= 20; i++)
if (i % 2 == 0)
System.out.println(i + "" "" + i*i);
-
for (int i = 0; i <= 10; i++)
if (i*i < 2*i + 4)
System.out.println(i + "" "" + i*i);
else
i = 11;
-
int i = 20;
while (i > 0)
{
System.out.println(i + "" "" + i*i);
i--;
}
| |