i=int(input("Enter Number to find sum of cube of digits: "))
sum=0
while(i>0):
sum=sum+(i%10)*(i%10)*(i%10)
i=i//10
print("Sum of cube of each digits=",sum)
Output:
Enter Number to find sum of cube of digits: 123
Sum of cube of each digits= 36
Explanation:
What does this program do?
It finds the sum of cube of each digits of a number entered by the user.
Example:
If the number is 123, the sum is 1 + 8 + 27 = 36
Line-by-Line Explanation
1. Input from user
i = int(input(“Enter Number to find sum of cube 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 cube of digits: 123
2. Initialize sum
sum = 0
- This variable sum will store the sum of cube 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)*(i % 10)
- i % 10 gives the last digit of the number
Example:
- (123 % 10) * (123 % 10) * (123 % 10) = 3 * 3 * 3 = 27
- (12 % 10) * (12 % 10) * (12 % 10) = 2 * 2 * 2 = 8
- (1 % 10) * (1 % 10) * (1 % 10) = 1 * 1 * 1 = 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) * (i % 10) * (i % 10) | sum value |
| 123 | 27 | 0 + 27 = 27 |
| 12 | 8 | 27 + 8 = 35 |
| 1 | 1 | 35 + 1 = 36 |
| 0 | loop ends |
6. Output
print(“Sum of cube of each digits =”, sum)
Output:
Sum of cube of each digits = 36
Final Result
Enter Number to find sum of square of digits: 123
Sum of Square of each digits= 36
Mathematical Explanation
For input 123: