Sum of digits in a number

This program is much similar to this one: Find product of digits in a number. The only difference is instead of multiply we have to perform addition here.

Logic

First of all, we are declaring one variable sum with value 0, we are going to use this variable to store the sum of all digits, now after taking input from the user, inside the while loop, we have to extract each digit by performing modulo operation.

The modulo operation returns the remainder after dividing a number by another number. If we perform modulo operation with 10 on any number it will return the last most digit, we have to add it into variable sum and store the result again in variable sum.

After that remove the last most digit from the number and perform the same again until the number becomes 0 or less than 0. Once the loop is completed simply print the variable sum containing the sum of all digit.

Program

#include <stdio.h>

int main() {

    int num, temp, sum = 0;

    // Take numbers from user
    printf("Enter any number : ");
    scanf("%d", &num);

    // Store to temporary variable.
    temp = num;
    
    while(temp != 0) {
        
        sum += temp % 10;

        // Remove last digit of 'temp'
        temp /= 10;
    }

    printf("\nSum of all digits in %d : %d", num, sum);

    return 0;
}

Output

Enter any number : 123456
Sum of all digits in 123456 : 21