I tried to solve the problem by calculating sum
up to n
without knowing about the base case and come up with this. It works but I don't know why.
int sumUpTo(int num)
{
int i, sum = 0; // I also tried not to initialize sum here but the results are the same
for(i = 0; i < num; i++)
sum = sumUpTo(num - 1) + num;
return sum;
}
int main()
{
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("Sum = %d\n", sumUpTo(num));
return 0;
}
I figured out that this function has the stopping condition i=num
but no base case, the loop will stop with sum = sumUpTo(0) + 1 + ... + num
. How could the program work without knowing the value of sumUpTo(0)
?
What could possibly happen here?
Did the program assume the value of sumUpTo(0)
is 0 (even with/without initialization of the variable sum
)?