CS 305j - Introduction to Computing
Discussion Assignment #2
1. What is the output for the following code? Figure out the answer
first, and then copy and paste the code into a file using BlueJ.
Compare your answer to the output you see after compiling and running
the program.
a)
int sum = 0;
for(int i = 0; i < 5; i++)
{
sum += i;
}
System.out.println(sum);
b)
for(int i = 1; i <= 5; i++)
System.out.println("How many lines");
System.out.println("are printed?");
c)
for(int i = 0; i < 5; i++)
{
for(int j = 0; j < 3; j++)
{
System.out.print("*");
}
System.out.println();
}
d)
for(int m = 1; m <= 5; m++)
{
for(int n = 1; n <= m; n++)
{
for(int p = n; p <= 3; p++)
{
System.out.print("#");
}
System.out.println();
System.out.print("*");
}
}
2. Write a static Java method that uses for loops to print the
following figure. It should be easy to modify your method to change the
length of each row or the number of rows.
***********
***********
***********
***********
3. What is the value of each expression in Java? Indicate the type of
the result as well as the value, i.e., write 3 for int, 3.0 for double,
"3" for string, '3' for char. If the expression will produce an error,
just write "error".
86592 % 10 % 100
5 + 2 * 4 - 4
10 / 4.0 * 2
4.2 % 4
3 * "result" + 6
1 - 2 + "number" + 8
("cat" + 2) * 4
"4" + "3" + "2" + "1"
14 / 5 / 2
4. For each part, indicate what expression should be used to print the indicated output.
for(int i = 1; i <= 7; i++)
System.out.print(<expression>);
a) 1, 2, 3, 4, 5, 6, 7
b) -4, -3, -2, -1, 0, 1, 2
c) 3, 7, 11, 15, 19, 23, 27
d) 15, 13, 11, 9, 7, 5, 3
5. Write a program that uses nested loops to print the following output.
*xxxxxxxx*
**xxxxxx**
***xxxx***
****xx****
**********
6. Now modify your program for #5 so that it prints:
*xxxxxxxxxxxxxx*
**xxxxxxxxxxxx**
***xxxxxxxxxx***
****xxxxxxxx****
...
*****************