by Dinesh Thakur Category: Control Structures

we determined the sum of digits of a non-negative integer number by determining the least significant digit and then removing it from given number.

 

In this example, we generalize this technique to determine the sum of digits of any non-negative integer number. To separate the digits of given number num, we can use a while loop as shown below:

while (num > 0)

digit = num % 10;

num /= 10;

In each iteration of this loop, the least significant digit of number num is separated in variable digit and then removed from the given number. The statements within this loop are executed as long as the value of num is greater than zero, i. e., as long as the number contains one or more digits.

Note that the value of digit will be modified in subsequent iterations. Thus, we should immediately add it to variable sum used to store the sum of digits. The variable sum should be initialized to zero before the loop. The program segment given below determines the sum of digits of the number num: ·

sum = 0;

while (num > 0)

digit = num % 10;

sum += digit;

num /= 10;

Note that this program works correctly even if the given number is zero. The complete program given below accepts a number from the keyboard, determines the sum of its digits and prints the sum.

#include <stdio.h>

void main()

{

        int num,digit,sum;

        clrscr();

        printf("Enter positive numbers:\n");

        scanf("%d",&num);

        sum=0;

        while (num > 0)

                {

                digit = num % 10;

                sum += digit;

                num /= 10;

                }

                    printf ("Sum Digit = %d ", sum);

                    getch();

}

               C Program Sum of Digits of a Given Integer Number



About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.



Search Content





Popular Article