Quiz #2 Prep

advertisement
Computer Science & Programming (CS 04.103-3)
Quiz #2 Prep Questions
1. Evaluate each expression below if a is 10, b is 12, c is 8, and flag is false. (1 point each)
a. (c == (a * b)) || !flag
(8 == (10 * 12)) || !false
(8 == 120) || !false
(false || !false)
(false || true)
true
b. (a != 7) && false || ((a + c) <= 20)
(10 != 7) && false || ((10 + 8) <= 20)
(10 != 7) && false || (18 <= 20)
true && false || true
false || true
true
c. !(b <= 12) && (a % 2 == 0)
!(12 <= 12) && (10 % 2 == 0)
!(12 <= 12) && (0 == 0)
!(true) && (true)
false && true
false
d. !((a < 5) || (c < (a + b)))
!((10 < 5) || ( 8 < (10 + 12) ))
!((10 < 5) || ( 8 < 22 ))
!(false || true)
!(true)
false
2. Write your own absolute value function that returns the absolute value of its input
argument. (5 points)
int myabs(int n)
{
int r;
if (n < 0)
r = - n;
else
r = n;
return r;
}
04 Mar 2011
Page 1 of 4
Computer Science & Programming (CS 04.103-3)
Quiz #2 Prep Questions
3. What is the output of the following code segment? (5 points)
a. char color = ‘R’;
b. switch (color)
c. {
d.
case ‘R’:
e.
cout << “Red” << endl;
f.
case ‘B’:
g.
cout << “Blue” << endl;
h.
case ‘G’:
i.
cout << “Green” << endl;
j.
default:
k.
cout << “Unknown” << endl;
l. }
Red
Blue
Green
Unknown
(No break statements!!!)
4. What is the output of the following code segment? (5 points)
a.
b.
c.
d.
e.
f.
g.
h.
i.
j.
k.
int n, ev, sum;
n = 11;
ev = 0;
sum = 0;
while (ev < n)
{
cout << ev << endl;
sum = sum + ev;
ev = ev + 2;
}
cout << ev << “ “ << sum << endl;
(This is the sequence of values for the variables.)
n: 11
ev: 0 2 4 6 8 10 12
sum: 0 0 2 6 12 20 30
(This is the output.)
0
2
4
6
8
10
12 30
04 Mar 2011
Page 2 of 4
Computer Science & Programming (CS 04.103-3)
Quiz #2 Prep Questions
5. Write nested for loops that display the following output. (10 points)
0
01
012
0123
01234
for (row = 0; row <= 4; ++ row)
{
for( col = 0; col <= row; ++ col)
cout << col << “ “;
cout << endl;
}
6. Write the prototype for a void function named pass that has two integer
parameters. The first parameter should be a value parameter and the second a
reference parameter. (5 points)
void pass(int a, int& b);
7. Write a code segment that allows the user to enter values and displays the number of
positive and negative values entered. Use zero as the sentinel value. Use a do loop. (10
points)
const int SENTINEL = 0;
int n;
int negcnt, poscnt;
negcnt = 0;
poscnt = 0;
do
{
cout << “enter a value: “;
cin >> n;
if (n < 0)
negcnt = negcnt + 1;
else
if (n > 0)
poscnt = poscnt + 1;
} while (n != SENTINEL);
cout << “Neg vals: “ << negcnt << endl;
cout << “Pos vals: “ << poscnt << endl;
04 Mar 2011
Page 3 of 4
Computer Science & Programming (CS 04.103-3)
Quiz #2 Prep Questions
8. List and explain three computational errors that may occur in type float
expressions. (6 points)
See representational error, cancellation error, & arithmetic underflow/overflow on
pages 391-393 in the text book.
04 Mar 2011
Page 4 of 4
Download