![]() |
CSC 215 |
|
Sample midterm questions |
Listed below are solutions to the sample questions I posted earlier.
double average(double a, double b)that returns the average of a and b.
Solution:
double average(double a, double b) { return (a + b) / 2.0; }
int minimum(int i, int j)that returns the smaller of i and j.
Solution:
int minimum(int i, int j) { if (i < j) { return i; } else { return j; } }
double convert(double Britishpounds)where Britishpounds contains an amount in British pounds sterling; the function should return what that amount is in US dollars. The conversion rate is 0.66 pounds per dollar.
Solution:
double convert(double Britishpounds) { const double rate = 0.66; return Britishpounds / rate; }
int sum(int n)that returns the sum of the integers from 1 to n.
int sum(int i, int n) { int answer = 0; int index; for (index = i; index <= n; index++) { answer += index; } return answer; }
int getMonth()that prints the prompt "Please enter a month: " and then accepts only a value between 1 and 12. It should work by looping until the user enters a legal value. It then returns the user's answer.
int getMonth() { int answer; do { cout << "Please enter a month: "; cin >> answer; } while (answer < 1 || answer > 12); return answer; }
// // // #include <iostream.h> int square(int n); int main() { int index; int limit = 5; int answer = 0; for (index = 1; index <= limit; index++) { cout << index << ", " << square(index) << endl; answer = answer + square(index); } cout << answer << endl; return 0; } int square(int n) { int answer; answer = n * n; return answer; }The program prints:
1, 1 2, 4 3, 9 4, 16 5, 25 55
// // // #include <iostream.h> int main() { int value = 32; while (value > 1) { cout << value << endl; value = value / 2; } return 0; }The program prints:
32 16 8 4 2