Cover Image for Add Digits of Number in C
93 views

Add Digits of Number in C

To add the digits of a number in C, you can extract each digit one by one and accumulate their sum. Here’s a C program to add the digits of a given number:

C
#include <stdio.h>

int main() {
    int num, originalNum, remainder, sum = 0;

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

    originalNum = num;

    // Calculate the sum of digits
    while (num != 0) {
        remainder = num % 10; // Get the last digit
        sum += remainder;     // Add the digit to the sum
        num /= 10;           // Remove the last digit
    }

    // Display the sum
    printf("Sum of digits of %d = %d\n", originalNum, sum);

    return 0;
}

In this program:

  1. We input an integer (num) from the user.
  2. We create a variable originalNum to store the original number for later display.
  3. We use a while loop to repeatedly extract the last digit of num, add it to the sum, and remove the last digit by dividing num by 10.
  4. The loop continues until num becomes 0, indicating that all digits have been processed.
  5. Finally, we display the sum of the digits.

For example, if the user enters the number 12345, the program will calculate and display the sum of its digits, which is 1 + 2 + 3 + 4 + 5 = 15.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS