Assignment 2: Detailed Solutions
Question 1: Writing Function Headers
You are asked to write the headers (signatures) for four functions. A “function header” in C+
+ includes the return type, function name, and parameter list (with types), but no body.
1. (i) Function check
Requirement:
- Two parameters:
1. an integer number
2. a floating-point number
- Returns no value.
Header:
void check(int number, float value);
Explanation:
- The return type is void because it “returns no value.”
- The first parameter is int number (an integer).
- The second parameter is float value (a floating-point number).
- The names number and value are arbitrary but descriptive.
2. (ii) Function mult
Requirement:
- Two parameters, both floating-point (float).
- Returns the result of multiplying them.
Header:
, float mult(float a, float b);
Explanation:
- The return type is float, since multiplying two floats yields a float.
- The two parameters are float a and float b.
- Inside the body (not shown), one would write return a * b;.
3. (iii) Function time (inputs and returns three values)
Requirement:
- Inputs seconds, minutes, and hours and returns them via parameters.
- In C++, to return multiple values, use reference parameters.
Header:
void getTime(int& seconds, int& minutes, int& hours);
Explanation:
- Return type is void, because values are returned via the reference parameters.
- Each parameter is int& (reference to an integer), so assignments inside the function
update the caller’s variables.
- Renamed from time to getTime to avoid conflict with std::time().
- If strictly required to name it time, you could write:
void time(int& seconds, int& minutes, int& hours);
4. (iv) Function countChar
Requirement:
- Returns the number of occurrences of a character in a string.
- Both the string and the character are provided as parameters.
Header:
int countChar(const std::string& text, char target);
Explanation:
, - Return type is int, because we count how many times target appears in text.
- The first parameter is const std::string& text: passed by constant reference to avoid
copying and ensure it is not modified.
- The second parameter is char target: a single character to count.
- Inside the function (not shown), iterate through text, increment a counter when a
character matches target, then return the counter.
Question 2: Finding and Correcting Errors
Below are six code segments. For each one, errors are identified and explained, followed by
a corrected version (or explanation of the fix).
(i)
Original:
int function1()
{
cout << "Inside function function1 " <<
endl; int function2()
{
cout << "Inside function function1 " << endl;
}
}
Errors:
- Nested function definition: You cannot define function2 inside function1 in C++.
- Missing return in function1 (should return int).
- The message in function2 mentions function1; likely meant to say function2.
Fix:
#include <iostream>
using namespace std;