Question

Sum of Digits of a Number using do while in C language

Updated on May 31, 2025 | By Learnzy Admin | πŸ‘οΈ Views: 329 students

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:

  1. The program takes an integer input from the user.
  2. A do-while loop is used to process each digit:
  3. In each iteration, the last digit of the number is obtained by using the modulus operator (number % 10).
  4. This digit is added to the sum.
  5. The number is then divided by 10 (removing the last digit) using integer division (number / 10).
  6. The loop continues until the number becomes zero.
  7. 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

Β 

Was this solution helpful? 37
Click here to download practice questions on do while in C

More Questions on do while in C

Question 1

Reverse a Number using do while in C language


View solution
Question 2

Print Numbers from 1 to 10 using do while loop


View solution