CS 10: Introduction to Computer
Programming
In-Class Examination I
Open-Book, 75 minutes, Spring 1997
General Instructions
Please put your answer to each question on its page. The examination is
designed to determine how well you know the material. Your goal is to get
as many points as possible (out of a possible 100 points). Please keep
this goal in mind as you budget your time.
Read each question carefully. Make sure that you clearly understand a question
before answering it. You may wish to work out an answer on scratch paper
before writing it on your answer page; answers that are difficult to read
may lose points for that reason.
Name:
Perm:
Question
|
Value
|
Score
|
1
|
10
|
|
2
|
10
|
|
3
|
10
|
|
4
|
10
|
|
5
|
10
|
|
6
|
10
|
|
7
|
10
|
|
8
|
10
|
|
9
|
10
|
|
10
|
10
|
|
Total
|
100
|
|
1. What is the output of the following code fragment?
while ( i*i < 5) {
g.drawString("i = " + y, 25, y);
y += 15;
i += 3;
}
2. Convert each of the following
using an assignment operator (e.g., +=, -=, *=, /=, %=). If this
cannot be done, say "It can't be done".
-
xyz = xyz +�zyx;
-
xyz = zyx +�xyz;
-
x = 3 - x;
-
x = x*a +�3;
-
xyz = (a - 5)*xyz;
3. Convert
the following while loop
fragment to an equivalent for
loop. If it can't be done,
say "It can't be done".
double x = 0.0;
while ( x <= 1.1 ) {
sum += x;
x += 0.2;
}
4. Convert the following
for loop
fragment to an equivalent while
loop. If it can't be done,
say "It can't be done".
for (int j = 100; j*j > 40; j -= 10)
{
sum += j %�3;
j += 5;
}
5. Convert the following code
using a switch statement.
The variable x is
an int.
if (x >= 0 && x < 250)
// use a switch for the part that starts here
if (x < 50)
g.setColor(Color.black);
else if (x < 100)
g.setColor(Color.red);
else if (x < 150)
g.setColor(Color.blue);
else if (x < 200)
g.setColor(Color.yellow);
else
g.setColor(Color.green);
// and ends here
6. What is the output of the following
code fragment?
int sum = 0, i = 0, y = 10;
while (++i < 6) {
switch (i*i % 4) {
case 0:
continue;
case 1:
sum += 2;
case 2:
sum += i*i %�3;
default:
sum += i*i % 3;
}
g.drawString("sum
= "�+�sum, 25, y);
y += 15;
}
7. Convert the following code
fragment to an equivalent one that does not use a continue.
Draw a picture of the result.
for (int i = 0; i < 10; i++)
for (int j = 0; j <�10;
j++)
if (j < i)
continue;
else
g.fillRect(15*j, 15*i, 10, 10);
8. Convert the following nested
if statements
to one that uses boolean operators. If it can't be done, say "It
can't be done".
if (john >= 16)
if ( mary >= 16)
if (oscar != 20.0)
sum = term;
if (mary <= 5)
sum = term;
else
sum = factor;
9. What is the output of the following
code fragment?
int i = 0, y = 10;
do {
g.drawString("i =
"�+�i, 25, y);
y += 15;
}
while (i++ < 0);
10. Give the Java code for an applet
that draws a solid blue rectangle of size 35 X 35 pixels wherever the user
clicks on the applet. The applet should be empty until a mouse click
occurs.