PART A - Short Answers (5 Marks) : Identifier Missing (Exchange of Int and Const Is Allowed!)
PART A - Short Answers (5 Marks) : Identifier Missing (Exchange of Int and Const Is Allowed!)
Question 1 [5 marks]
Find at least 5 errors in the following main() and correct them. You can add explanation on the right
int main () {
int const = 30; identifier missing (exchange of int and const is allowed!)
int x = 2.5; double assigned to an int (not a syntax error though)
while x < 10 { brackets missing around the condition
sum = sum + x ; sum not declared
if (sum = 0) ; 1) double equal (==) 2) no semicolon
cout << "zero sum";
else {
x = x+1;
Z = Z+2; Z not declared nor initialized
cout << x , Z; replace , by <<
}
} } missing
Question 2 [5 marks]
int i = n;
while (i >= 1){
cout << i;
i = i/2;
}
b) What is the output produced if n contains the value 15? Output: 15 7 3 1 (no spaces)
Question 3 [4 marks]
The following piece of code aims at depositing or withdrawing a maximum of $1000 into/from a
bank account. Rewrite it using a combination of switch and if statements.
Question 4 [3 marks]
In the code below, complete the statement in bold by using the substr() function to remove the
character at position i in the string word (Hint: concatenate what’s before position i and what’s after it )
int main(){
int num1 = 5;
int num2 = 10;
int result = do_something (num1, num2);
cout << num1 << num2 << result; output: 5 11 15 (no spaces)
}
Question 7 [3 marks]
int main(){
int A[6] = {10, 20, 30, 40, 50, 60};
int B[6];
* 2 bonus marks will be given if you use a do-while loop to ensure the numbers are distinct.
int main(){
int a, b, c;
do {
cout << "Please enter 3 distinct numbers ";
cin >> a >> b >> c;
} while (a==b || b==c | a==c);
int sum = a + b + c;
cout << "their sum is: " << sum << endl;
int smallest = a;
if (b < smallest)
smallest = b;
if (c < smallest)
smallest = c;
cout << "The smallest number is: " << smallest << endl;
cout << "the sum of the larger two is: " << sum - smallest;
}
Question 9 [12 marks]
a) Write a complete C++ function that takes a number n as a parameter. The function reads n
integers entered by the user, and calculates and returns the alternating sum of these integers.
For example, if n = 5, and the user enters 3,7,8,2,6, your function should compute + 3 – 7 +
8 – 2 + 6, and returns the sum 8.
int main () {
cout << "The alternating sum of the numbers is: " << alt_sum(5);
}
or
or
Or