Loops (with solutions)
Indicate
the output that will be produced for each exercise. For questions 1 to 15,
assume the following declarations are made just before each exercise. That is,
assume these initializations are in effect at the beginning of each problem:
double MIN =
10;
double MAX =
20;
double
num = 15;
1. while
(num < MAX) 15
{ 16
System.out.println
(num); 17
num = num + 1; 18
} 19
2. while
(num < MAX) 16
{ 17
num = num + 1; 18
System.out.println
(num); 19
} 20
3. do 16
{ 17
num = num + 1; 18
System.out.println
(num); 19
} 20
while
(num <= MAX); 21
4. while
(num < MAX) 15
{ 14
System.out.println
(num); 13
num = num - 1; infinitely…
}
5. while
(num > MIN) 15
{ 14
System.out.println
(num); 13
num = num - 1; 12
} 11
6. while
(num < MAX) 15
{ 17
System.out.println
(num); 19
num += 2;
}
7. while
(num < MAX) 16
{ 18
if (num%2 == 0)
System.out.println
(num);
num++;
}
8. do 21
{
num = num + 1;
if (num*2 > MAX+num)
System.out.println
(num);
}
while
(num <= MAX);
9. for
(int value=0; value >= 7; value++) no output
System.out.println
(value);
10. for
(int value=7; value < 0; value--) no output
System.out.println
(value);
11. for
(int value=1; value <= 20; value+=4) 1
System.out.println
(value); 5
9
13
17
12. for
(int value=num; value <= MAX; value++) 15
System.out.println
(value); 16
17
18
19
20
13. for
(int value=num; value <= MAX; value++) 15
if (value%4 != 0) 17
System.out.println
(value); 18
19
14. for
(int count1=1; count1 <= 7; count1++)
{
for (int count2=1;
count2 <= 5; count2++)
System.out.print
("#");
System.out.println();
}
#####
#####
#####
#####
#####
#####
#####
15. for
(int count1=1; count1 <= 5; count1++)
{
for (int count2=1;
count2 <= 5; count2++)
System.out.print
(count1*count2 + " ");
System.out.println();
}
1 2 3
4 5
2 4
6 8 10
3 6
9 12 15
4 8
12 16 20
5 10
15 20 25
16. char
ch = ‘z’;
final
double TOLERANCE = 0.000001;
double
val = 1.0;
switch (ch)
{
case ‘a’:
if (val > 0.0)
System.out.println(“apple”);
break;
case ‘b’:
if (val < 5.0)
System.out.println(“orange”);
break;
case ‘z’:
if (Math.abs(val –
1.0) < TOLERANCE)
System.out.println(“pear”);
else
System.out.println(“peach”);
break;
default:
System.out.println(“grape”);
}
pear
17. int num4 = 1;
while
((num4 – 1) >= 0)
{
switch (num4)
{
case 1:
num4 = num4 + 1;
break;
case 3:
num4 = num4 – 4;
break;
default:
num4 = num4 + 1;
}
System.out.println
(num4);
}
System.out.println
(“out of loop”);
2
3
-1
out of loop
18. final
int MM = 3;
boolean b = false;
for
(int c = MM; c >= 0; c--)
{
switch (c)
{
case 1:
b = !b;
break;
case 2:
System.out.println(c);
break;
default:
if (b) b = !b;
}
}
System.out.println(“out of loop”);
if
(!b) System.out.println(“no”);
2
out of loop
no