C Program to Find Sum of Digits of a Number

1. Introduction

Finding the sum of the digits of a number is a common programming exercise and also finds applications in digital root calculations. The digital root of a number is the iterative process of summing its digits until a single-digit number is achieved. In this tutorial, we will develop a C program that calculates the sum of digits of an input number.

2. Program Overview

1. Take an integer input from the user.

2. Initialize a sum variable to zero.

3. Iteratively extract each digit of the number and add it to the sum while the number is not zero.

4. Display the sum of the digits.

3. Code Program

#include <stdio.h>

int main() {
    int num, sum = 0, temp;

    // Get the number from the user
    printf("Enter an integer: ");
    scanf("%d", &num);

    // Store the original number
    temp = num;

    // Calculate the sum of digits
    while(temp != 0) {
        sum += temp % 10;  // Extract the last digit
        temp /= 10;       // Remove the last digit
    }

    printf("Sum of digits of %d is %d\n", num, sum);
    return 0;
}

Output:

Enter an integer: 12345
Sum of digits of 12345 is 15

4. Step By Step Explanation

1. We start by prompting the user to enter an integer.

2. We use a while loop to iterate as long as the number is not zero. In each iteration:

- We use the modulus operator (%) to extract the last digit of the number and add it to our sum.

- We then divide the number by 10 to remove its last digit.

3. Once the loop finishes, the variable 'sum' contains the sum of all the digits of the original number.

4. We display the result to the user.

Comments