Let Us C / Chapter 6 (Data Types Revisited)

                               Exercise [D]


Following program calculates the sum of digits of the number 12345. Go through it and find out why is it necessary to declare the storage class of the variable sum as static.
main( )
{
int a ;
a = sumdig ( 12345 ) ;
printf ( "\n%d", a ) ;
}
sumdig ( int num )
{
static int sum ;
int a, b ;
a = num % 10 ;
b = ( num - a ) / 10 ;
sum = sum + a ;
if ( b != 0 )
sumdig ( b ) ;
else
return ( sum ) ;
}

Solution:


#include<stdio.h>
#include<conio.h>

void main() {

int a;

clrscr();

a=sumdig ( 12345 ) ;

printf("\n %d ",a) ;

getch();

}
sumdig(int num)
{

static int sum;

/*

It is necessary to declare the storage class of sum as static because it is within
a recursive funtion. It is necessary to keep the value of 'num' same for all relevent
recursions of it. And to obtain running sum of all of them.

*/

int a,b;

a=num%10;
b=(num-a)/10;
sum=sum+a;

if(b!=0)
sumdig(b);

else
return(sum);

}
______________________________________________________________________

No comments:

Post a Comment

Let Us C / Chapter 7 (The C Pre-processor)

                               Exercise [C] (a) Write down macro definitions for the following: 1. To test whether a character ente...