Python Program to Find Sum of all Digits of Given Number Using While Loop

In this post, we are going to write a Python program to find the sum of all digits of a given number using a while loop.

In mathematics, the sum of the digits of a number is the sum of all its individual digits.

So, here is a program to find the sum of all digits of a given number using a while loop.

Simple Code:

num = int(input("Enter a number: "))
sum_of_digits = 0
while num > 0:
    digit = num % 10
    sum_of_digits += digit
    num //= 10
print("The sum of digits of the given number is:", sum_of_digits)

Output:

Enter a number: 456986
The sum of digits of the given number is: 38

Code With Explanation:

# Take input of the number
num = int(input("Enter a number: "))
# Set initial sum to 0
sum_of_digits = 0
# Loop until the number is non-zero
while num > 0:
    # Get the last digit of the number
    digit = num % 10
    # Add the digit to the sum of digits
    sum_of_digits += digit
    # Remove the last digit from the number
    num //= 10
# Print the sum of digits of the given number
print("The sum of digits of the given number is:", sum_of_digits)

Explanation:

The program takes an input of a number and uses a while loop to find the sum of all its digits.

The while loop continues until the number becomes zero.

In each iteration, the last digit of the number is obtained using the modulus operator (%).

This digit is then added to the sum of digits.

Finally, the last digit is removed from the number using integer division (//).

This process continues until all digits have been processed.

Finally, the program prints the sum of the digits of the given number.

Was this helpful?
YesNo

Related Articles:

Recent Articles:

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x