1

So below is my code, I'm having some difficulties trying to put my knowledge on recursion functions into use. My program wants to find the sum all the natural numbers, using the users input as the last number.

I have tried to use a recursion function but it doesn't seem to work. In my eyes the problem is that once function calls its self again the integer total doesn't seem to remember it's initial value. Can someone please help me out.

include <stdio.h>

int sum(int); 

main(){
    int a; 
    printf("Enter your number\n");
    scanf_s("%d", &a); 
    printf("The answer is %d", sum(a)); 
    getch();
}

int sum(int a){ 
    int total = 0;
    total = total + a;  /*add the new value of a*/
    a--;    /*decrease the value of a by one*/
    if (a == 0){
        return total;   /* leave the function and display this value */
    }
    else {
        sum(a); /*call this function again */
    }
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
CoolDude
  • 131
  • 1
  • 2
  • 10
  • 1
    Is this homework? Is so pass `total` as a parameter. If not - avoid recursion – Ed Heal Feb 20 '16 at 00:32
  • 2
    Of course it doesn't. Total is local variable. Local variable is local even if you call the function recursively. It is like variable of any other function. – Andrey Feb 20 '16 at 00:33
  • Be careful with how you return values from the function. You're missing something. – e0k Feb 20 '16 at 00:33
  • this isn't homework guys, I study Electrical Engineering. This is just a skill that i am learning. I have made a code that does the outcome of this task and i didn't need a function to do that, i just just used a for loop in the main body and it worked fine. I want to get the hang of recursion functions so that's why i'm doing this. – CoolDude Feb 20 '16 at 00:46

3 Answers3

5

Let's write a definition of the sum() function in words:

The sum of all natural numbers up to n is n plus the sum of the natural numbers up to n-1.

Notice that this definition is recursive because I need to calculate the sum for a smaller number in order to calculate the sum for a given number. Using this as a guide, we might try something like this:

int sum(int n) {
    return n + sum(n - 1);
}

If you try to run this with some test code, you will get a stackoverflow. This is because we have not given a base case to tell when the iteration stops. This base case is implicit in our definition above. The smallest natural number is zero. We are simulating natural numbers with the int type which stores integers. So we need to modify our code slightly to make sure we do not allow negative integers:

int sum(int n) {
    if (n <= 0)
        return 0;

    return n + sum(n - 1);
}

I think part of the problem you are encountering is that you want to use an accumulator. Often with recursive solutions this is not necessary since the recursive call can immediately return the accumulated value.

Analysis:

Let's take a look at how this works with an example:

void main() {
    int x = sum(3);

    printf("%d\n", x);
}

Level 1

The first line calls sum() and sets n to 3.

int sum(int n) {
    if (n <= 0)

n is not less than or equal to zero, so we skip to the return

        return 0;

    return n + sum(n - 1)

Now we call sum() again with a value of n-1 which is 2

}

Level 2

Now sum() is evaluated with n set to 2.

int sum(int n) {
    if (n <= 0)

Again we skip the if statement.

        return 0;

    return n + sum(n - 1);

And sum() is called with a value of 1.

}

Level 3

int sum(int n) {
    if (n <= 0)

Since n is 1, we skip the if.

        return 0;

    return n + sum(n - 1);

Now we call sum(0).

}

Level 4

int sum(int n) {
    if (n <= 0)
        return 0;

Since n is 0, we return 0. This sends execution back to

Level 3

    return n + sum(n - 1);

On this level n is 1 and Level 4 returned a value of 0. Adding these together and we return a value of 1 back to Level 2.

Level 2

    return n + sum(n - 1);

On this level n is 2 and Level 3 returned a value of 1. Adding these together and we return a value of 3 back to Level 1.

Level 1

    return n + sum(n - 1);

On this level n is 3 and Level 2 returned a value of 3. Adding these together and we return a value of 6 back to main().

    printf("%d\n", x);

Finally, main() prints the value of x which was set to 6.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
2

You have two problems.

First, every time you call the function, you're initializing the local variable total to 0. So it's not calculating a total across all the calls, it starts from 0 every time you make the recursive call. You need to pass the total as an argument, so that you can add to it.

Second, when you make the recursive calls, you're not doing anything with the result that it returns. You need to return its value back up the chain.

include

int sum(int, int); 

main(){
    int a; 
    printf("Enter your number\n");
    scanf_s("%d", &a); 
    printf("The answer is %d", sum(a, 0)); 
    getch();
}

int sum(int a, int total){ 
    total = total + a;  /*add the new value of a*/
    a--;    /*decrease the value of a by one*/
    if (a == 0){
        return total;   /* leave the function and display this value */
    }
    else {
        return sum(a, total); /*call this function again */
    }
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • You have answered my question the best Mr. Barmar, thanks a lot. You have also pointed out my mistake which was reinitialising the total value and hence making it redundant! Your explanation is brilliant! Thanks a lot – CoolDude Feb 20 '16 at 01:07
1

If you intend to add the values you should do it somewhere, try

int
sum(int n)
{
    if (n == 0)
        return n;
    return n + sum(n - 1); // Add the current value to the sum of the values
                           // from n - 1 to 0.
}

Your function also, causes infinite recursion because you always pass a to the sum() function so a == 0 would be only true if you start with n == 0.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
  • How about return `n + sum(n - 1)?` – Andrey Feb 20 '16 at 00:34
  • Yes that's very clear although I wanted to make it as similar as possible to the OP's code. This function doesn't make any sense because you can compute the sum in a single step too, but that's irrelevant. – Iharob Al Asimi Feb 20 '16 at 00:35
  • I'm trying to learn C guys and learn the recursion function. I know you can just do this using a simple For loop in fact i have actually done it using a FOR loop in my main body but i want to use recursion functions. Iharob, when i do what you suggested it still gives me the same answer. I think the total variable doesn't remember it's initial value so it just takes the new value. Can you suggest something else please Andrey you are correct but i don't like that solution and need to learn it this way :( – CoolDude Feb 20 '16 at 00:50
  • @bahjat Local variables do not maintain their values across function calls unless declared with the `static` storage specifier. You don't need the function to remember anything, just try to write the function in a paper as a recursive expression, you can do that to. If you succeed you will easily write the recursive function you need. – Iharob Al Asimi Feb 20 '16 at 01:22
  • @bahjat And you don't need any loops at all, the sum of all the natural numbers from `1` to `N` is simply `N(N + 1)/2`, [Gauss found out that when he was 7 years old](http://www.storyofmathematics.com/19th_gauss.html). It was widely known of course, it's not that Gauss discovered it. – Iharob Al Asimi Feb 20 '16 at 01:28
  • @iharob Thank you for suggesting i do it on paper, i did it on paper and i finally understand it! I'd like to say thank you to everyone who helped me out on this problem, i really do appreciate it guys. Thanks a lot – CoolDude Feb 20 '16 at 12:45