You are on page 1of 1

Homework Assignment 3

These are short answer questions. State your answers concisely. Submit your answers to these questions as a
PDF document via Canvas by the due date.
1. Consider the following two Java loops:
while (x > 0) {
y++;
x--;
}

do {
y++;
x--;
} while (x > 0)

If x is set to 5 and y is set to zero before each loop, what are are the values of y at the end of each loop?
What if both variables are initialized to zero prior to each loop?
2.

Consider the following two Java code segments:

int x = 0;
int y = 0;
while (x < 10) {
y++;
x++
}

int y = 0;
for(int x = 0; x < 10; x++) {
y++;
}

What are the values of y after the loops are completed? Are there any differences between the two
pieces of code?
3. Suppose you have the following methods:

void x(int [] a) {
for (int i = 0; i < a.length; i++)
a[i]++;
}
}
void y (int a) {
a++;
}

Suppose you have the following code using methods x and y:


int [] b = {0, 1, 2, 3};
int c = 1;
x(b);
y(c);

Are the values of b and c changed after the calls to method x and y? Why is there a difference?
4. Consider the following code:
int a[];
System.out.println(a[0]):

What is wrong with this code?


5. Consider the following code:

int [] b = {0,1,2,3,4,5,6,7};
for(int i : b)
System.out.println(i);

What does this for loop do?


6. Explain the difference between break and continue when used inside a loop.
7. How would you allocate storage for the integer array a[][] so that it has four rows, the first having 3
elements, the second having five elements, the third six elements, and the fourth row having seven
elements. Show the code.
8. Consider the methods
1) double max (double, double)
2) double max (int, int)

Which method is called by each of the following staements? Explain why.


a.
b.
c.

max(1, 2.0);
max(7, 8);
max(3.0, 2.1);

You might also like