Write a C program to accept an integer and display its sum of digits.

Sum of digits in a C program allows a user to enter any number, divide that number into individual numbers, and sum those individual numbers.

Example 1:

Given number = 142 => 1 + 4 + 2 = 7.

Sum of digits of a given number “142” is 7.

#include <stdio.h>
int main(void)
{
    int num, sum = 0, rem;
    printf("Enter a number: ");
    scanf("%d", &num);
    // Keep dividing until the number is not zero
    while (num != 0)
    {
        rem = num % 10;
        sum = sum + rem;
        num = num / 10;
    }
    printf("Sum of digits of the number is %d", sum);
    return 0;
}
OUTPUT:
Enter a number: 162
Sum of digits of the number is 9

0 Comments:

Post a Comment