|
- Problem 1:
- Rewrite the following program segment as a single if-else statement.
if (n < 5)
x = x + n;
if (n >= 5)
x = x - n;
- Problem 2:
- Rewrite the following program segment using nested conditional statements.
if (p > 0) g.drawString("positive", 50, 50);
if (p == 0) g.drawString("zero", 50, 50);
if (p < 0) g.drawString("negative", 50, 50);
- Problem 3:
- Find the error in the following if-statement and correct it.
if (x && y == 0)
g.drawString("That's the origin.", 50, 50);
- Problem 4:
- Explain what the following program segment does, and then correct it so that it does what it was meant to do. (Hint: See page 90 of the textbook, and add a pair of braces { and }.)
if (x == y)
if (x == 0)
g.drawString("x and y are both zero.", 50, 50);
else
g.drawString("x and y are not equal.", 50, 50);
- Problem 5:
- What is the output of the following program segment?
a = 1; b = 5;
while (a > 0)
{ a = a + b;
b = b - 3;
System.out.println(a + " and " + b);
}
(Recall that System.out.println( ); prints exactly one line of output on the "console screen" (not in the graphics window) and then scrolls the screen up one line. It is more convenient to use than g.drawString( ); when there are several lines of output to be printed.)
- Problem 6:
- What is the output of the following program segment?
i = -1; j = 2;
while (i + j < 5)
{ while ( j < 5)
{ System.out.println(i + " and " + j);
j = j + 2;
}
i = i + 2;
j = j - 3;
}
- Problem 7:
- What is the output from the following program segment?
for (i = 2; i <= 5; i++)
for (j = 5; j > i; j = j-1);
System.out.println(i + " and " + j);
- Problem 8:
- Will the following for-loop ever terminate? If it does, what is its output? If it does not, give the first 10 lines of its output.
n = 5;
for ( i = 1; i <= n; i++)
{ System.out.println(i + " and " n);
n = n + 1;
}
- Problem 9:
- Write a Java method that computes the mathematical function
g(x,y) = |x-y| + 2x/(1-y).
- Problem 10:
- Write a Java method that has as its inputs two doubles and a positive integer n, and returns true if the doubles are both contained in the interval [-n, n], and returns false otherwise.
- Problem 11:
- Write a program segment that declares and constructs an array, and then uses a loop to initialize the array with the following numbers.
-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5
- Problem 12:
- An array called numbers is declared and constructed by the following line.
int[] numbers new int[10]
Suppose that this array is then initialized with random integers. Describe as best you can what the following program segment does. For example, after each loop around the for-loop, how would you describe the value of x? Also, how would you describe the output of this code?
int x = numbers[0];
for (i = 1; i < 10; i++)
if (numbers[i] >= x)
x = numbers[i];
System.out.println(x);
|
|