Question
Sum of Digits of a Number using do while in C language
Solution
β Verified
This C program calculates the sum of digits of a given number using a do-while loop. The program extracts each digit of the number by repeatedly dividing the number by 10 and taking the remainder. This remainder is the last digit of the number.
How it works:
- The program takes an integer input from the user.
- A do-while loop is used to process each digit:
- In each iteration, the last digit of the number is obtained by using the modulus operator (number % 10).
- This digit is added to the sum.
- The number is then divided by 10 (removing the last digit) using integer division (number / 10).
- The loop continues until the number becomes zero.
- Once all digits have been processed, the total sum of the digits is printed.
#include <stdio.h>
int main() {
int num, sum = 0, digit;
printf("Enter a number: ");
scanf("%d", &num);
do {
digit = num % 10;
sum += digit;
num /= 10;
} while (num != 0);
printf("Sum of digits = %d\n", sum);
return 0;
}
Output-
Enter a number: 465
Sum of digits = 15
Β
Click here to download practice questions on
do while in C