Ok. I'm pretty new to C (and programming in general). I started 5 months ago. I have this code:
Code:
#include <stdio.h>
#include <stdlib.h>
/* I'm Lazy */
typedef unsigned long int BIG;
BIG Sum(BIG n);
int main(int argc, char *argv[])
{
BIG n;
if(argc<2) /*check for argument*/
return(0);
n=atoi(argv[1]); /*convert to an integer*/
printf("\nAnswer = %d\n",Sum(n));
return(0);
}
BIG Sum(BIG n)
{
BIG result; /*final result variable*/
if (n>0)
{
printf("Calling Sum(%d)\n",n);
result = n+Sum(n-1);
/* after all Sum() functions are called, they start returning, returning, returning... :-) */
printf("Sum() is returning. Partial result= %d\n",result);
return(result);
}
else /*indicates the end of calling all the Sum() functions*/
{
printf("\nFinished Calling Sum(). Return 0\n\n" );
return(0);
}
}
It will get a number from the user (inputed as an argument) and it will sum all the numbers from 1 to the number. Example: 4 -> 4+3+2+1 = 10.
I entered some printf() functions to understand how recursiveness works, and I'm all set on that part. The only problem is when I put a number like 99,999. The function gets called, and called, and called 'till 34,906 and then the program crashes and exits.
Why does this happen? I mean, I can also do it like this:
Code:
BIG Sum(BIG n)
{
BIG result;
for(result=0;n>0;n--)
{
result+=n;
}
return(result);
}
But why do recursive functions die like that? Thanks a lot.