0

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)); 
    }
}
user2116243
  • 303
  • 2
  • 10

2 Answers2

0

There is no any need to use a static variable. The function could look the following way

#include <stdio.h>
#include <stdlib.h>

int digits_sum( int x )
{
    const int Base = 10;
    int digit = abs( x % Base );

    return ( x /= Base ) ? digit + digits_sum( x ) : digit;
}

int main(void) 
{
    int x = 123456789;

    printf( "%d\n", digits_sum( x ) );

    return 0;
}

The program output is

45

As for the static variable then it is initialized only once when the function is first time called and is accessible for all other calls of the function. That is it is a shared variable among function calls. You can consider it as a global variable relative to the function body. This variable has the static storage duration opposite to (local) variables with the automatic storage duration

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

The static variable sum of function find_digits is allocated in global address space. It is initialized to zero at the start of the program execution (or set to its initializer value by the linker).

The variable is not alocated on the stack. In your example, the value of this static variable is pushed onto the stack (calls to printf).

The variable is the same in every call to find_digits, that is, the function operates on just one variable (memory address), independent of the recursion depth.'

With "123" as input, sum is first set to 3, then in the next call to find_digits, it is incremented by 2 to 5, then by 1 to 6, then the recursion unwinds and to sum (which is now 6) is added the return value of find_digits, which is sum (which is 6), is now is 12, to which is added the return value of find_digits (whch is sum, which is now 12), so is 24.

Paul Ogilvie
  • 25,048
  • 4
  • 23
  • 41