Thursday, November 17, 2011

1CIT0101 Exercise

Question 1


a) What is a variable? How are they used in computer programs?

(3 marks)


b) What is output by the following lines of code?

divisor = 5;
value = ( 8 * 4 * 2 + 16 ) / 2 + 4;
cout << value << “ % ” << divisor << “ = ”
       << value % divisor;

(5 marks)


c) Write a complete C++ program to calculate and display the coordinates of the midpoint of the line connecting the two points whose coordinates are (3, 7) and (8, 12). Use the fact that the coordinates of the midpoint between two points having coordinates (x1, y1) and (x2, y2) are ((x1 + x2)/2, (y1 + y2)/2). The display produced by your program should be:
The x coordinate of the midpoint is xxx.xx
The y coordinate of the midpoint is xxx.xx

where xxx.xx denotes that the calculated value should be placed in a field wide enough for three places to the left of the decimal point, and two places to the right of it.

(12 marks)
(Total: 20 marks)


Question 2

a) Under what circumstances would the default case in a switch statement execute? What would happen under those circumstances if there is not a default case?

(4 marks)

b) What does the following program print?

1 #include
2 #include
3 using namespace std;
4
5 int main()
6 {
7 int y;
8 int x = 1;
9 int total = 0;
10
11 while ( x <= 10 )
12 {
13 y = pow(x, 2);
14 cout << y << endl;
15 total += y;
16 x++;
17 }
18
19 cout << "Total is " << total << endl;
20 return 0;
21 }

(4 marks)
(Total: 12 marks)



Question 3

a) For the following code segment, determine if there is an error in the code. If there is an error, identify the line where the error has occurred, specify the nature of the error, and then write the corrected code. If the code does not contain an error, write “no error”.

The following while loop should compute the product of all integers between 1 and 5, inclusive:

1 int i = 1;
2 int product = 1;
3
4 while (i <= 5);
5 product += i;

(6 marks)


b) Four experiments are performed, each experiment consisting of three test results. Write a complete C++ program using a nested for loop to enter each experiment’s test results and then compute and display the average of the test results for each experiment.

Sample output:

Experiment 1

Enter test result: 23.2
Enter test result: 31
Enter test result: 16.9
Experiment 1 average: 23.7



Experiment 2

Enter test result: 34.8
Enter test result: 45.2
Enter test result: 27.1
Experiment 2 average: 35.7



Experiment 3

Enter test result: 19.4
Enter test result: 16.8
Enter test result: 10
Experiment 3 average: 15.4



Experiment 4

Enter test result: 36.9
Enter test result: 39
Enter test result: 49.2
Experiment 4 average: 41.7

(14 marks)
(Total: 20 marks)