|
- 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:
- What is the output of the following program segment if
a) pos=8, neg=-5, and value=2,
b) pos=29, neg=-10, and value=0.
if (value > 0)
pos = pos + value;
else
neg = neg + value;
System.out.println(pos + " and " + neg);
- Problem 3:
- Rewrite the following program segment using nested conditional statements.
if (p > 0) System.out.println("positive");
if (p == 0) System.out.println("zero");
if (p < 0) System.out.println("negative");
Why is it better to rewrite this using nested conditional statements?
- Problem 4:
- 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);
}
- Problem 5:
- The following program segment prints out the first 10 odd integers.
n = 10; i = 0;
while (i <= 2*n - 1)
{ i = i + 2;
System.out.println(i);
}
What would be the output if we had forgotten to include the two braces { and }?
- 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:
- The following while-loop prints out the first 10 odd integers. Rewrite it as a for-loop two different ways.
n = 10; i = 1;
while (i <= 2*n - 1)
{ System.out.println(i);
i = i + 2;
}
- 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 function that computes the mathematical function
g(x,y) = |x-y| + 2x/(1-y).
- Problem 10:
- Write a Java function 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 for-loop to initialize the array with the following set of 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);
|
|