bananabread76
bananabread76

Reputation: 37

Recursive function to sum numbers inbetween two others

I want to sum each number inbetween two others (e.g. 1 to 5 would be sum = 9, 2+3+4), but my function always returns 0 and I honestly don't understand why. Hope you can help me, thanks. Here's my code:

#include <stdio.h>

int inbetween_sum (int N1, int N2);

int main (int argc, char **argv) {
    int n1, n2, sum;
    printf("n1:\n");
    scanf("%d", &n1);
    printf("n2:\n");
    scanf("%d", &n2);
    sum = inbetween_sum(n1, n2);
    printf("%d", sum);
    return 0;
}

int inbetween_sum (int N1, int N2) {
    int sum1 = 0;
    if (N1 == N2) {
       return sum1;
   }
   sum1 += inbetween_sum (N1+1, N2);
   return sum1;
}

Upvotes: 1

Views: 111

Answers (2)

Mohit Jain
Mohit Jain

Reputation: 30489

Line sum1 += inbetween_sum (N1+1, N2); is faulty. All you ever return or add is 0 and never the actual number.

Rewrite your function as:

int inbetween_sum (int N1, int N2) {
   int sum1 = 0;
   if (N1 >= N2 - 1) {
       return sum1;
   }
   sum1 += N1 + 1 + inbetween_sum (N1+1, N2);
   return sum1;
}

Live example here

Upvotes: 3

woru
woru

Reputation: 1420

You are adding zeros. You have to add N1 + 1 to your sum and change stop condition

int inbetween_sum (int N1, int N2) {
   int sum1 = 0;
   if (N1 + 1 >= N2) {
      return sum1;
   }
   sum1 += N1 + 1 + inbetween_sum (N1+1, N2);
   return sum1;
}

Also initializing sum1 to 0 and then using += is not clear. Your code can be refactored to:

int inbetween_sum (int N1, int N2) {
   if (N1 + 1 >= N2) {
      return 0;
   }
   return N1 + 1 + inbetween_sum (N1+1, N2);
}

Upvotes: 3

Related Questions