Hi everyone, a few months ago my professor gave us a problem which I didn't manage to solve, then I forgot about it but now I found it again and I'm still stuck with it, the problem is:
given a prototype: int sum (int (*f) (int), int start, int end);
/* Post sum(f,start,end)= ∑i = start, i = start+1, .... i = end f(i) *\
Implement recursively the funcion sum and show how it has to be called in order to output
∑i = 1, ... i = N g(i) where g is a function which prototype is int g(int).
I wrote this code:
Code:
#include <stdio.h>
int g(int n)
{
return n*(n+1) / 2;
}
int sum(int (*f)(int), int start, int end)
{
if(start==end) return f(start);
return sum(f, start+1, end);
}
int main()
{
int start, end, result;
scanf("%d%d", &start, &end);
result = sum(g, start, end);
printf("%d\n", result);
return 0;
}
However I'm not sure this is the right way to solve it, if someone can give me a few hints I would really appreciate it since i guess my professor is going to give us a similar problem in the next exam, thanks