Jung Jae Won
Jung Jae Won

Reputation: 57

Recursive Function to find sum of nth term using C

#include <stdio.h>

#define for noIter
#define while noIter

int sumUP(int n)
{
int result;

if (n == -1)
{
    return 0;
}

return result + (3 * sumUP(n - 1) + 2);

int main(){
    
    int n = 0, ret;
    
    while(1){
        printf("Enter a positive integer : ");
        scanf("%d", &n);
        if(n < 0)
            break;
        ret = sumUP(n);
        printf("Sum up to %dth term = %d\n", n, ret);
    }
    
    return 0;
}

I am currently making a program which sums up the term using recursive function. I have programmed few lines but it shows some weird results. The general form of sequence term is 3n + 2 thus when the user enter integer 5 then the result displayed should be 55 (17 + 14 + 11 + 8 + 5). Hereby program should be stopped when the user inputs -1.

I was able to design a condition which will stop the loop when user inputs -1 but I am struggling with the recursive function. What should I change it in order to have correct outputs?

Upvotes: 0

Views: 580

Answers (1)

MikeCAT
MikeCAT

Reputation: 75062

Based on the facts

  • One term is 3n+2
  • sumUP(n) will return the sum

The line

return result + (3 * sumUP(n - 1) + 2);

should be

return n <= 0 ? 0 : ((3 * n + 2) + sumUP(n - 1));
}

So that it will return results of addition of one term and sum of left terms when there are terms and return 0 when there are no terms. Also don't forget the }.

One more point is that #define while noIter should be removed or the while(1){ and corresponding } in the main function should be changed to mainloop: and goto mainloop; to have it compile.

Upvotes: 4

Related Questions