Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

10/10/12

add digits of number in c | Programming Simplified

Home C programming C programming examples add digits of number in c

add digits of number in c


C program to add digits of a number: Here we are using modulus operator(%) to extract individual digits of number and adding them.

C programming code
# i n c l u d e< s t d i o . h > m a i n ( ) { i n tn ,s u m=0 ,r e m a i n d e r ; p r i n t f ( " E n t e ra ni n t e g e r \ n " ) ; s c a n f ( " % d " , & n ) ; w h i l e ( n! =0 ) { r e m a i n d e r=n%1 0 ; s u m=s u m+r e m a i n d e r ; n=n/1 0 ; } p r i n t f ( " S u mo fd i g i t so fe n t e r e dn u m b e r=% d \ n " , s u m ) ; r e t u r n0 ; }

For example if the input is 98, sum(variable) is 0 initially 98%10 = 8 (% is modulus operator which gives us remainder when 98 is divided by 10). sum = sum + remainder so sum = 8 now. 98/10 = 9 because in c whenever we divide integer by another integer we get an integer. 9%10 = 9 sum = 8(previous value) + 9 sum = 17 9/10 = 0. So finally n = 0, loop ends we get the required sum. Output of program:

Add digits using recursion


# i n c l u d e< s t d i o . h > i n ta d d _ d i g i t s ( i n t ) ; i n tm a i n ( ){ i n tn ,r e s u l t ; s c a n f ( " % d " ,& n ) ;

www.programmingsimplified.com/c/program/c-program-add-number-digits

r e s u l t=a d d _ d i g i t s ( n ) ;

1/2

10/10/12
r e s u l t=a d d _ d i g i t s ( n ) ; p r i n t f ( " % d \ n " ,r e s u l t ) ; r e t u r n0 ; } i n ta d d _ d i g i t s ( i n tn ){ s t a t i ci n ts u m=0 ; i f( n= =0 ){ r e t u r n0 ; } s u m=n % 1 0+a d d _ d i g i t s ( n / 1 0 ) ; r e t u r ns u m ; } C programming: C programming examples

add digits of number in c | Programming Simplified

Guest (not verified)


Wed, 29/06/2011 - 21:06 per m a lin k

output for this program


output for this program
reply

Guest (not verified)


Mon, 10/10/2011 - 17:54 per m a lin k

Something is wrong?
try the input "1 00". The output should be 1 right? but in y our code, I don't think so.
reply

adminPs
Tue, 11/10/2011 22:39 per m a lin k

ouptut is 1
For 1 00 input output is 1
reply

Guest (not verified)


Mon, 10/10/2011 - 18:30 per m a lin k

NOT WORKING
This program is not working correctly
reply

adminPs
Tue, 11/10/2011 22:45 per m a lin k

Program works fine


The code correctly prints the desired output.
reply

www.programmingsimplified.com/c/program/c-program-add-number-digits

2/2

You might also like