CS 1400 Intro. to Computer Science Summer 2007 Dr. Cannon KEY 1. (15 pts) Show the output results of the execution of each of the following fragments. Each of these segments is to be considered independently.

a) int cost = 15; cost *= 4; cout << “cost is: “ << cost; 60

b) int rate = 50; rate = rate / 6 + 2.5; cout << “rate is: “ << rate; 10

c) for (int n=0; n<2; n++) hello for (int k=0; k<2; k++) hello cout << “hello\n”; hello hello

2. (15 pts) The following program outputs 10 lines representing the integers 1 through 10 and their square roots. Modify this program so that the output goes to the disk file “roots.txt” instead of to the console.

#include #include #include using namespace std; int main() { ofstream fout;

fout.open (“roots.txt”);

fout << “Square Roots of 1 through 10: \n”; for (int n=1; n<=10; n++) fout << n << “, “ << sqrt(n) << endl; }

3. (20 pts) Write a complete program that prompts the user for a floating-point centigrade temperature. Convert this temperature into Fahrenheit. Output the converted temperature rounded to two decimal places. The algebraic formula is:

9 f  (c)  32 5 #include #include using namespace std; int main() { float cent, fahr; cout << “Enter centigrade temp: “; cin >> cent; fahr = (9 / 5.0) * c + 32; cout << setprecision(2) << fixed << “Fahrenheit conversion is : “ << fahr << endl; } CS 1400 Intro. to Computer Science Summer 2007 Dr. Cannon 4. (15 pts) Complete the following program to output the message “The number is not valid” if the variable temperature input by the user is outside the range 0 through 80.

#include using namespace std; int main() { int temperature; cout << “Enter a temperature in the range 0 through 80: “; cin >> temperature;

if (temperature < 0 || temperature > 80) cout << “The number is not valid\n”;

return 0; }

5. (10 pts) The following program contains at least one error. Find and correct any errors so that this program outputs the sum of the integers 1 through 100.

#include using namespace std; int main() { int sum = 0; for (int count=1; count<=100; count++) sum += count; cout << “The sum is: “ << sum << endl; return 0; }

6. (15 pts) True/False all are True

a) The while loop is a pretest loop. b) The for loop is a pretest loop. c) In a nested loop, the inner loop goes through all of its iterations for every single iteration of the outer loop. d) Arguments are passed to a function in the order they appear in the function call. e) The scope of a parameter is limited to the function which uses it (or in which it is declared).

7. (10 pts) Consider the following program fragment:

{ cout << “Enter a paygrade: “; cin >> paygrade; switch (paygrade) { case 1: case 2: cout << “worker\n”; break; case 3: cout << “management\n”; break; case 4: cout << “boss\n”; } What would be the output of this fragment for the following input numbers? a) 1 worker b) 4 boss