You are on page 1of 3

Mekelle University – Computer Science Department

C++ Exam – Time Allowed: 2 hours

(Instructor: Andy King)

Name: ID:

Answer all of the questions. The maximum score is 100. You may use notes and
handouts, but you may not use any C++ textbook.

1) Compute the value of each legal C++ arithmetic expression. If the expression is not
legal, explain why. Clearly indicate what the data type of the result of each expression
would be.

a) (1.0 / 4) * 6
b) (6 * 3) % 5
c) (3 / 4) * 4
d) (4.0 * 2) % 5
e) ((10 + 5 / 2) / 3)

(3 marks each – 15 marks total)

2) Write a C++ program that reads in an integer number x from the user, and prints out
the value of the following expression:

(x + 5) * (x + 5)
-----------------
(x + 3)

The program should first check if x is equal to -3. If it is, then the message “Error!”
should be printed to the screen instead of the result.

(16 marks)

3) Write a program that uses a C++ for loop to add up all of the even integers between
11 and 41, and prints the result.

(16 marks)

4) What would be the output of the following program? Write your answer exactly as it
would appear on the screen.
#include <iostream.h>

int cube (int x);

main () {
int i, j, t;
t = 0;
for (i = 0; i < 5; i++) {
j = cube (i);
cout << i << “: “ << j << endl;
t += j;
}
cout << “t = “ << t << endl;
}

int cube (int x)


{
return (x * x * x);
}

(18 marks)

5) The following program is supposed to read in a sequence of integer numbers from the
keyboard, and print the square root of each one. The program should terminate when
the user enters the number –1. However, the code contains 5 errors. Examine the
code, and state what you think the errors are. Clearly explain how you would correct
the errors to make the program work.

#include <iostream.h>
#include <math.h>

main ()
{
int number;
while (cin > num) {
if (num = -1)
break;
cout << sqrt (num) << end;
}

(15 marks)

6) Write a definition for a C++ class called FBE. The class should contain:
a) 2 private integer data members called x and y.
b) a public member function called func, which takes one floating point value as an
argument, and returns no value.
c) a constructor and a destructor which take no arguments.

Note: you do not need to write the function body for func: only write the class
definition.

(20 marks)

You might also like