C Sum of Digits Program


The Sum of Digits program calculates the sum of all individual digits of a given integer. For example, if the input number is 123, the output will be 1 + 2 + 3 = 6.

Logic of the Sum of Digits Program:

  1. Input a number from the user.
  2. Initialize a variable to hold the sum of the digits.
  3. Extract each digit of the number using modulus and division operations:
    • Use the modulus operator % to get the last digit.
    • Add this digit to the sum.
    • Use integer division / to remove the last digit.
  4. Repeat until all digits have been processed (when the number becomes zero).
  5. Print the final sum of the digits.

Program:

Here’s a C program to calculate the sum of digits of a given number:

#include <stdio.h> int main() { int num, sum = 0, remainder; // Input a number from the user printf("Enter an integer: "); scanf("%d", &num); // Make sure to handle negative numbers num = (num < 0) ? -num : num; // Convert to positive if negative // Calculate the sum of digits while (num != 0) { remainder = num % 10; // Get the last digit sum += remainder; // Add the last digit to the sum num /= 10; // Remove the last digit } // Output the result printf("Sum of the digits is: %d\n", sum); return 0; }

Explanation:

  1. Variables:

    • int num: Holds the number inputted by the user.
    • int sum: Initializes to zero and will accumulate the sum of the digits.
    • int remainder: Used to store the current digit being processed.
  2. Input:

    • The program prompts the user to enter an integer.
  3. Handling Negative Numbers:

    • The program converts the number to positive if it is negative using the conditional operator.
  4. Sum Calculation:

    • A while loop runs until num becomes zero.
    • Inside the loop:
      • The last digit of num is obtained using num % 10.
      • This digit is added to sum.
      • The last digit is removed from num using num /= 10.
  5. Output:

    • Finally, the program prints the total sum of the digits.

Sample Output:

Example 1:

Enter an integer: 123 Sum of the digits is: 6

Example 2:

Enter an integer: -456 Sum of the digits is: 15

Example 3:

Enter an integer: 1001 Sum of the digits is: 2

Key Points:

  • Digit Extraction: The program effectively extracts each digit from the number using modulus and division.
  • Handling Negatives: It gracefully handles negative input by converting it to positive before processing.
  • Efficiency: The program runs in linear time relative to the number of digits in the input number, making it efficient for this operation.
  • User Interaction: The program is user-friendly, prompting for input and providing clear output.