Lab3 Ex2. Fold And Fold Again
You cannot submit for this problem because the homework's deadline is due.
Ex2. Fold And Fold Again
Related Topics: Recursion, Function pointer.
In this exercise, you will need to implement the fold function below, where count
is the number of elements in the arr
array, fn
points to a function, which takes in two int
s and returns an int
, and initial
is a value. You are welcomed to write a helper function for the recursion.
```cpp
int fold (int count, int arr[], int (*fn) (int, int), int initial) {
}
```
If count == 0
, just return the initial
value. Otherwise, take count = 3
for example, the return value could have been equivalently calculated as follows:
int temp1 = fn(arr[0],initial)
int temp2 = fn(arr[1],temp1)
int temp3 = fn(arr[2],temp2)
return temp3
In short, the fold
function will take each element in the array as well as the previous return value, until we have gone through the whole array. And it will return the last calculated value.
To help you understand how the fold
function works, write two fn
functions to be used with the fold
function:
- a function called fn_add
such that fold(n, arr, fn_add, 0)
returns the sum of the elements in arr
.
- a function called fn_count_odd
such that fold(n, arr, fn_count_odd, 0)
returns the number of odd numbers in arr
.
Hint: Please be aware that the order of inputs into the fn
function matters. The first one should be the element from the array, and the second one should be either the initial value or the previous return value of fn
.
Requirement: Please refer to ex2.cpp
in the starter_files
folder, you will need to implement fold
, fn_add
and fn_count_odd
functions. You only need to submit ex2.cpp
for this problem.
Lab Three: Recursion, Function Pointer and Program Arguments
- Status
- Finished
- Problems
- 3
- Open Since
- 2022-05-31 19:30
- DDL
- 2022-06-07 23:59
- Extension
- 72.0 hour(s)