Objective of the code: To return the sum of the digits of a number.
The following code returns 24 for 123, 50 for 1234, 90 for 12345. (Variable Sum is static) How to trace the output?
(6x4 = 24, 10x5 = 50, 15x6 = 90)
I am trying to understand how static variables are pushed onto the stack. (Is the variable pushed or its address?)
//sum of digits using recursion
#include<stdio.h>
int find_digits(int );
int main()
{
int num;
printf("Enter a number\n");
scanf("%d", &num);
int sum = 0;
printf("\nThe sum of the digits is %d", sum);
sum = find_digits(num);
printf("\nThe sum of the digits is %d", sum);
}
int find_digits(int num)
{
int digit = num%10;
printf("\nDigit is %d", digit);
static int sum=0;
sum += digit;
printf("\nsum is %d", sum);
if(num<=0)
{
printf("\n1. Num is %d and sum is %d", num, sum);
return sum;
}
else
{
printf("\n2. Num is %d and sum is %d", num, sum);
return (sum + find_digits(num/10));
}
}