Index « Previous Next »

Question

Write a program that asks the user to input a positive integer. Your program should find and display the sum of digits of number.

For example, sum of digits of number 32518 is 3+2+5+1+8 = 19.

Source Code

#include <stdio.h>

int main()
{
    int number, temp, remainder, sum = 0;

    printf("Enter a positive integer :");
    scanf("%d", &number);

    temp = number;

    while (temp > 0)
    {
        remainder = temp % 10;
        sum += remainder;
        temp /= 10;
    }

    printf("sum of digits of number %d is %d", number, sum);

    return 0;
}

Output

Enter a positive integer :4562
sum of digits of number 4562 is 17