1

I'm new to coding, working my way through week 3 of cs50X. I'm trying to teach myself how to write recursive functions, as they spent a lot of time explaining the theory behind recursion in the lecture but not much in terms of how to practically write it, including when and where to call a function within itself. Anyway, I am trying to write a recursive function to calculate the sum of integers from 1 to n, but every time I run what I have below, I get 1 number higher than the correct answer. Can anyone point out what I did wrong? Any help would be much appreciated :)

// The sum of ints 1-5 should be 15, but I keep getting 16. Why?

#include <stdio.h>

int numPrint(int);

int main(void)
{
    int n = 0;
    printf("The sum of all integers 1 - 5 is: ");
    printf("%i\n", numPrint(n));
    return 0;
}

int numPrint(int n)
{
    if (n > 5)
    {
        return 1;
    }
    else
    {
        return (n + numPrint(n + 1));
        //return numPrint(n + 1);
    }
}

2 Answers 2

1

The problem with your function is that when you get to the number "6", you still add 1 to the final sum, so that's why you keep getting the wanted result + 1.
You could do something like this:

int numPrint(int n)
{
    if (n > 5)
    {
        return 0;
    }
    else
    {
        return (n + numPrint(n + 1));
        //return numPrint(n + 1);
    }
}

You got the right idea but I would change a few things about the way you implemented the function to make it useful in other cases. If you want to know the sum of the numbers between 1 and n, your function should use the argument n as highest number and not the lowest. That way you can change the value of n and you don't get limited by the "n>5" constraint you applied.
Like this:

#include <stdio.h>

int numPrint(int);

int main(void)
{
    int n = 5;
    printf("The sum of all integers 1 - 5 is: ");
    printf("%i\n", numPrint(n));
    return 0;
}

int numPrint(int n)
{
    if (n == 1)
    {
        return 1;
    }
    else
    {
        return (n + numPrint(n - 1));
    }
}
0

On the final recursion, it returns 1 which is added to the total on the way back out. At that point, it should return 0. Try working it out with paper and pencil, or insert print statements to show what is being passed in, and what will be returned, maybe even a persistent variable to track which call level it is on, if needed.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .