Sovi.AI - AI Math Tutor

Scan to solve math questions

QUESTION IMAGE

sum of digits by codechum admin write a program that takes an integer i…

Question

sum of digits
by codechum admin
write a program that takes an integer input from
the user and calculates the sum of its digits
using a while loop. the program should output
the result to the user.
sample output 1
enter an integer: 51
sum of digits: 6
sample output 2
enter an integer: 120
sum of digits: 3
sample output 3
enter an integer: 1562
sum of digits: 14

Explanation:

Step1: Get user input

num = int(input("Enter an integer: "))

Step2: Initialize sum

sum_digits = 0

Step3: Use while loop to calculate sum

while num > 0:
    digit = num % 10
    sum_digits += digit
    num = num // 10

Step4: Output the result

print(f"Sum of digits: {sum_digits}")

Answer:

num = int(input("Enter an integer: "))
sum_digits = 0
while num > 0:
    digit = num % 10
    sum_digits += digit
    num = num // 10
print(f"Sum of digits: {sum_digits}")