=========================preview======================
(COMP104)final98_sol.pdf
Back to COMP104 Login to download
======================================================
1) Modify the following code segment so that it displays the product of odd integers from 1 to n, inclusive. Mark your changes directly on the code. (5 marks)

int x = 0;
for (int i = 1; i < n; ++i) {
if (i % 2 == 0) {
x += i;
}
cout << x << endl;
}

Answer:

int x = 1 // 1 mark
for (int i = 1; i <= n; ++i) { // 1 mark
if (i % 2 == 1) { // 1 mark
x *= i; // 1 mark
}
}
cout << x << endl; // 1 mark

2) Write nested for loops that print out all of the 4-bit binary numbers. Format the output as shown below so that the numbers appear in a table with four numbers per line. (6 marks)

0000 0001 0010 0011
0100 0101 0110 0111
1000 1001 1010 1011
1100 1101 1110 1111

Answer:

for (int i=0; i<2; i++) { // 1 mark
for (int j=0; j<2; j++) { // 1 mark
for (int k=0; k<2; k++) { // 1 mark
for (int m=0; m<2; m++) { // 1 mark
cout << i << j << k << m; // 1 mark for these 2
cout << " "; // statements
}
}
cout << endl; // 1 mark
}
}

3) The following program is supposed to print out the contents of the file "text.dat" to the screen. Correct any bugs. Mark your corrections directly on the code. (3 marks)

#include <iostream>
#include <fstream>
using namespace std;
int main(){
ifstream file;
char c;
file.get(c);
while(!file.eof()){
cout << c;
file.get(c);
}
return 0;
}

Answer:

#include <iostream>
#include <fstream>
using namespace std;
int main(){
ifstream file;
file.open("text.dat") // 2 marks
char c;
file.get(c);
while(!file.eof()){
cout << c;
file.get(c);
}
file.close(); // 1 mark
return 0;
}

4) What is the output? (6 marks)

#include <iostream>
using namespace std;
void main(){
int a=3, b=2, c=9;
int *z, *y, *x;
x = &c;
*x = 8;
y = z = &b;
y = x;
*y = 5;
y = &a;
x = y;
*x = 4;
cout << a << " " << b << " " << c << " " << *x << " "
<< *y << " " << *z << endl;
}

Answer:
4 2 5 4 4 2 // 1 mark each


5) The following is the header of the copy constructor definition for a class called ABC. The identifier ABC occurs three times. What does each occurrence refer to? (3 marks)

ABC::ABC(const ABC& x)

Answer:
1st - class name // 1 mark
2nd - constructor name // 1 mark
3rd - parameter type // 1 mark
6) The following program tries to sort the array A[10] using selection sort. Unfortunately, it does not work: when the program returns, the elements in A are not sorted. Please correct the program so that it will output A's elements in the following sorted order: 1 1 2 4 7 8 9 10 11 13. (4 marks)

#include <iostream>
using namespace std;

void swap(int x, int y) {
int temp;
temp = x;
x = y;
y =