Input a number and find the sum of its digits. Input – 346 Output - 13
Answers
Answered by
0
n=int(input("Enter a number:"))
sum=0
#Program by Ankitraj707
while(n>0):
dig=n%10
sum=sum+dig
n=n//10
print("The total sum of digits is:",sum)
We are using while loop here.
We have assigned a variable sum=0 outside the while loop.
Under the while loop having condition n>0
We have dig=n%10 which will give the remainder or the last digit of a number.
Take an example of 123
Divide it by 10, what will be the remainder
123%10=3
Now,we have sum= sum +dig = 0+3=3
and we have n=n//10, here the value of n keeps changing until n=0
n= 123//10= 12
And now this value of n will go to dig=n%10= 12%10=2
And this get stored in sum.
And at last sum of 123 will be Printed.
Enter a number: 123
The total sum of digits is 6
Similar questions