COMP 11 - Introduction to Computer Science - Fall 2002

Study Guide for Exam 1

Note that the character _ represents a space, as in the string ``Joe__Smith'' has two spaces between the two names. This is used only when it's important.

Also, for all these outputs, be sure to show the output precisely, including spaces.

1.
Write down the value that C++ calculates for each of the following expressions. For number answers, be sure to show whether the answer is integer or floating point.
1. 8 - 2*3
2. 8*2 - 6/4
3. 3*6/4.0
4. 4*(7 - 3)
5. 6/4*2.0
6. 8 - 2.5*2
7. 3*5/2! = 7
8. 3 + 4 > 10  ||  3*4 > 10
9. 10%4 = = 2  &&  1 < 3/2
10. !(3 = = 10/3)
2.
What do the following code segments print? Assume that the necessary #include's are in the program.
2a.

string s = "Hello";

int k;

for (k=0; k<=2; k = k+1) s = s + "_" + "bye";

cout << s << endl;

Hello bye bye bye
2b.

int n = 0, m = 0, k;

cin >> k;

while (k>0) {

if (k %2 == 0) n = n + k;

else m++;

cin >> k;

}

cout << setiosflags(ios::right) << setw(6) << n;

cout << setiosflags(ios::left)  << setw(5) << m;

cout << "end" << endl;

For 2b, assume that the data typed to the program is:

7  14  19  3  6  0  17

____20____3end
2c.

int n = 13;

int k = 0;

int d = 3;

while (n>0) {

n = n - d;

k++;

}

if (n == 0) cout << k << ' ' << n << endl;

else cout << k-1 << ' ' << d+n << endl;

4 1
2d.
Re-run the code in 2c except let n be initialized to 15.
2e.

int m (int x, int y);

int g ();

int main () {

cout << m(g(), m(g(), g())) << endl;

}

int g () {

int x;

cin >> x;

return x;

}

int m (int x, int y) {

if (x > y) return x;

else return y;

}

The input to this program is as follows:

17  65  32
2f.

int x = 165, b = 10, e = 0, t = 1;

while (x>t) {

e++;

t = t * b;

}

cout << x << ' ' << e << endl;

165 3
2g.

for (char ch='A'; ch<'D'; ch++) {

for (int j=int(ch)-int('A')+1; j>0; j-) cout << ch;

cout << endl;

}

A

BB

CCC

3.
Write a program that calculates the range of some data that you will read from the keyboard. The data will be terminated by a sentinel of -1. The range is simply the difference between the largest number and the smallest number in the data. For example, if the data comprised the following 4 numbers - 20.0, 15.5, 5.0 and 19.0 - then the range would be 15.0, i.e., 20.0 - 5.0 = 15.0. You can assume that there is at least one datum.

Just write the main function; you can leave out the #include's and other ``stuff'' that is typically at the top of your programs. Furthermore, you need not include any comments but you should use good style (e.g., indentation).

4.
Write a program that read in 3 integers and prints out the largest one that is even. If none are even, then print out ``none''. Note that zero is even.

Again, just write the main function.

Webmaster for COMP 11