i=int(input("Enter Number to find sum of digits:"))
sum=0
while(i>0):
sum=sum+i%10
i=i//10
print("Sum of digits=",sum)
Output:
Enter Number to find sum of digits:123
Sum of digits= 6
Explanation:
What does this program do?
It finds the sum of digits of a number entered by the user.
Example:
If the number is 123, the sum is 1 + 2 + 3 = 6
Line-by-Line Explanation
1. Input from user
i = int(input(“Enter Number to find sum of digits: “))
- Takes a number from the user
- Converts it to an integer
- Stores it in variable i
Example input:
Enter Number to find sum of digits: 123
2. Initialize sum
sum = 0
- This variable will store the final sum of digits
3. While loop
while(i > 0):
- Loop runs until the number becomes 0
4. Get last digit
sum = sum + i % 10
- i % 10 gives the last digit of the number
Example:
- 123 % 10 = 3
- 12 % 10 = 2
- 1 % 10 = 1
5. Remove last digit
i = i // 10
- Removes the last digit using integer division
Example:
- 123 // 10 = 12
- 12 // 10 = 1
- 1 // 10 = 0
| i value | i % 10 | sum value |
| 123 | 3 | 0 + 3 = 3 |
| 12 | 2 | 3 + 2 =5 |
| 1 | 1 | 5 + 1 = 6 |
| 0 | loop ends |
6. Output
print(“Sum of digits =”, sum)
Output:
Sum of digits = 6
Final Result
Enter Number to find sum of digits:123
Sum of digits= 6