Here, we need to calculate the sum of the digits of a number, For example, take 123 and we have to find the sum as ' 1 + 2 + 3 = 6 '
To apply this program logic in python, we need to open an while loop
until the number is less than zero. We have to take the digit from the integer by using the mod operator and calculate the sum as sum + digit. Then we have to remove one digit from the number by dividing it by 10. Finally, we print the result after all the iterations of the while loop.
STEP 1: Accept the user's input using the input function and convert that string to an integer using int()
.
STEP 2: Initialize the sum as zero.
STEP 3: Open a while loop
till the number is less than zero.
STEP 4: Take one digit from the number using the mod operator.
STEP 5: Calculate the sum as sum + digit.
STEP 6: Remove the digit from the integer by dividing it by 10.
STEP 7: Print the result using the print statement.
To find the sum of digits in python, we need to know the below concepts, please refer to those for a better understanding
n=int(input("Enter a number:"))
sum=0
while(n>0):
dig=n
sum=sum+dig
n=n//10
print("The sum of digits in the number is:",sum)
Enter a number : 123 The sum of digits in the number is: 6