#include <stdio.h>
int sum(int n, int s)
{
while (n)
{
s+=n/n+1;
n--;
}
return s;
}
int main()
{
int n=8;
int s=0;
int result;
result=sum(n, s);
printf("%d ", result);
getchar();
return 0;
}
Im supposed to write a recursive function that takes an integer n as a parameter and returns the sum of the first n elements in the following sequence,
½ + 2/3 + ¾ …. + n/n+1
The name of the function should be sum. I am also supposed to include a call to this function from main, with n=8 and then print the result in main.
float sum(float x, float n=1,float d=2) {
if(x) {
float s = n/d;
cout << n <<"/"<<d<<" ="<<s<< endl; //comment this out if you dont want to display
return s+sum(x-1,n+1, d+1);
} elsereturn 0;
}
#include <stdio.h>
int sum(int n, int s)
{
while(n)
{
s+=sum(n/n+1);
n--;
}
return s;
}
int main()
{
int n = 8;
int s=0, result;
result=sum(n, s);
printf("%d ", result);
getchar();
return 0;
}
The errors are gone . However, the program isn't printing out the correct numbers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <stdio.h>
int sum(int n, int s)
{
if(n)
{
s+=sum(s,n/n+1);
n--;
}
}
int main()
{
int n = 8;
int s=0, result;
result=sum(n, s);
printf("%d ", result);
getchar();
return 0;
}