COMP248 Tutorial 07
COMP248 Tutorial 07
Question 1:
What is the output of the following code segments?
A.
for (int i = 1; ++i < 4;)
System.out.print(i);
B.
for (int i = 1; i < 4; i++)
System.out.print(i);
C.
for (int i = 1; i++ < 4;)
System.out.print(i);
D.
for (int i = 1; i < 4; ++i)
System.out.print(i);
1
E.
for (int j = 0; j <= 2; j++) //outer loop
{
System.out.print(j);
for (char ch = 'A'; ch <= 'M'; ch += (3+j)) //inner loop
System.out.print((char)(ch + 1));
System.out.println();
}
F.
for (int i = 1;i < 9;i++)
{
if (i % 2 == 0) System.out.println(i + 1);
else if (i % 3 == 0) continue;
else if (i % 5 == 0) break;
else System.out.println("Not multiple of 2, 3 or 5.");
}
System.out.println ("End");
H.
int sum = 0;
for (int k = 0; k < 7; k++)
{
for (int j = 7; j > 2 * k; j -= 2)
{
System.out.print(" " + (j - k) + "+");
sum += (j - k);
}
System.out.println();
}
System.out.println(" = " + sum);
2
Question 2:
Assume the following program:
public class Increment
{
public static void main(String[] args)
{
int prevprev = 2, prev = 2, sum = 0;
for (int i = 1; i < 4; i++)
{
sum = prevprev + prev;
System.out.println(prevprev + " " + prev + " " + sum);
prevprev = prev;
prev = sum;
}
}
}
A.
What is the output of this program?
3
B.
If we replace the for with the following lines, will the output be the same? If the
output will be different, what will it be?
Question 3:
A.
Use a for loop (10000 iteration) and % symbol to find odd numbers.
B.
Use a for loop (10000 iteration) but don’t use % symbol to find odd numbers.
Question 4:
Write a program that prints the numbers from 1 to 100. But for multiples of three
print “Fizz” instead of the number and for the multiples of five print “Buzz”. For
numbers which are multiples of both three and five print “FizzBuzz”.
4
Question 5:
Write programs to draw the following shapes:
A.
*
**
***
****
*****
B.
*
***
*****
*******
*********
Question 6:
Write a nested for loop to display the following output:
a b c d e
a b c d
a b c
a b
a
5
Question 7:
Write a program that will display the following multiplication table.
1 2 3 4 5 6 7 8 9
2 4 6 8 10 12 14 16 18
3 6 9 12 15 18 21 24 27
4 8 12 16 20 24 28 32 36
5 10 15 20 25 30 35 40 45
6 12 18 24 30 36 42 48 54
7 14 21 28 35 42 49 56 63
8 16 24 32 40 48 56 64 72
9 18 27 36 45 54 63 72 81