Thursday, 15 August 2013

Chapter 6 solutions Problem [D]

Question-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 sumas 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-
I have come to the 6th chapter of the book.
Well, this is the only question I should solve in this chapter. This chapter can actually be ignored , unless you want to be an extraordinary programmer , there is nothing much in this chapter. you can make Program without knowing, all the stuff this chapter covers . I have thought of posting some output questions, which I will found tricky. let's first see the solution of this question.

"This program can be generalized, and it's a good alter for the loop program for finding the sum of number.so, in the first step value= 12345 passed to the function.function calculates a,b.
after first operation the value of b is non-zero. so, it goes for if statement and again calls the function. now, if you don't use "static" ,sum value obtained by "(sum=sum+a)" would be lost in next call and it will again start from beginning. one more advantage we get is, we need not to initialize sum, since static variables already have Default initial value 0. otherwise in auto if would print random values, which certainly we don't want here. "

No comments:

Post a Comment