I am having trouble understanding how the recursion in following code works. So I do understand that main
prints the user input. Then the function sigma
will print +
and a decrementation of m
until it reaches 0
.
When it reaches 0
it will print =
and the variable answer. What I do not understand is how return calculates the numbers together. Could anybody please explain how the return is doing this?
#include <cs50.h>
#include <stdio.h>
int sigma(int m)
{
printf("%i", m);
if (m == 0)
{
printf("=");
return 0;
}
else
{
printf("+");
return (m + sigma(m - 1));
}
}
int main(void)
{
int n = GetInt();
int answer = sigma(n);
printf("%i\n", answer);
}