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);
}
}