Assessments 4 Tutorial Letter 2024
for
Introduction to Programming II
COS1512.
BARCODE
, COS1512 ASSESSMENT 4
NB: This assignment consists of two parts:
a part where you write and implement program code (this part) and
an MCQ part where you answer questions on the code you have written,
and the material covered in this assignment.
The MCQ part of the assignment will be available in the Assessment Shell for
Assignment 4 on the myModules site for COS1512.
You will not be able to do the MCQ part unless you have completed thecoding
part.
Question 1
The program below contains an incomplete recursive function raised_to_power().
The function returns the value of the first parameter number of type float raised to
the value of the second parameter power of type int for all values of power greater
than or equal to 0.
The algorithm used in this question to write a recursive function to raise a float
value number to a positive power uses repeated multiplication as follows:
numberpower =1 if power= 0
= number x numberpower-1 otherwise
In other words, number raised to power gives 1 if power i s 0;
and otherwise numberpower can be calculated with the formula:
number x numberpower-1
1. #include <iostream>using namespace std;
2. float raised_to_power( )
3. {
4. if (power < 0)
5. {
6. cout << "\nError - can't raise to a negative power\n";
7. exit(1);
9. }
10. else if ( )
11. return ( );
12. else
13. return (number * raised_to_power(number, power - 1));
14. }
15. main()
16.
17. float answer = raised_to_power(4.0,3);
18. cout << answer;
19. return 0;
20.}
(a) Complete the function header in line 2.
(b) Using the fact that any value raised to the power of 0 is 1, complete the base