CSC 221: Computer Programming I
Fall 2001

Test 2 Review Questions


QUESTION 1: What is output by the following program?

#include <iostream> using namespace std; void Func1() { cout << "Print 1" << endl; } void Func2() { Func1(); cout << "Print 2" << endl; } int main() { Func2(); cout << "Print 3" << endl; Func1(); cout << "Print 4" << endl; return 0; }


QUESTION 2: Write a code segment that reads in an integer (call it num) and outputs the word "positive" if num is greater than zero, "zero" if num is equal to zero, or "negative" if num is less than zero.


QUESTION 3:What is output by the following (somewhat tricky) code segment?

int foo = -1; if (foo < 0) { cout << "negative" << endl; foo = -foo; } if (foo == 0) { cout << "zero" << endl; } if (foo > 0) { cout << "positive" << endl; }


QUESTION 4: Consider the following code segment.

cin >> num; while (num <= 50) { <lots of fun stuff here> cin >> num; } // assertion:

At the point in the code labeled as an assertion, what must be true about the value of num?


QUESTION 5: What is output by the following code segment?

int n = 4, p = 1; while (n > 0) { p *= n; n--; cout << p << endl; }


QUESTION 6: Rewrite the following while loop as a for loop.

int value = 10; while (value < 1000) { cout << value << endl; value *= 2; }


QUESTION 7: Write a code segment that reads in a sequence of integers, terminated with a negative value, and outputs their sum. For example, if the user enters

4 6 13 0 3 -1 then your code should output 26. Note: the negative sentinel value should not be included in the sum.


QUESTION 8: Complete the function PrintReps whose header is given below:

void PrintReps(string name, int numReps) // Assumes: numReps >= 0 // Results: prints name numReps times, once per line


QUESTION 9: What is output by the following program?

#include <iostream> using namespace std; void Func(int x, int & y) { x += 5; y += x; cout << "Inside: " << x << " " << y << endl; } int main() { int a = 10, b = 20; Func(a, b); cout << "Outside: " << a << " " << b << endl; return 0; }


QUESTION 10: Suppose an array of doubles named values, size 100, has been declared and initialized. What would be the effect of executing the following code segment?

for (int i = 0; i < 100; i++) { values[i] *= 2; }


QUESTION 11: Suppose an array of doubles named values, size 100, has been declared and initialized. Write a segment of C++ code that would display the contents of the array in reverse order, one number per line of output. That is, the last number should be displayed on the first line, followed by the next-to-last number, and so on.


QUESTION 12: Complete the function SumElements whose header is given below:

int SumElements(int nums[], int numNums) // Assumes: nums contains numNums elements (numNums >= 0) // Returns: sum of all the integers in nums