Sum of Cube of Digits in C, C++, Java & Python – Code with Explanation & Examples in Short and Simple

   

C Program

#include <stdio.h>
int main() {
    int n, sum = 0, r;
    scanf("%d", &n);
    int temp = n;
    while (n > 0) {
        r = n % 10;
        sum += r * r * r;
        n /= 10;
    }
    printf("Sum of cube of digits of %d is %d", temp, sum);
    return 0;
}

C Output

Input:
123

Output:
Sum of cube of digits of 123 is 36


C++ Program

#include <iostream>
using namespace std;
int main() {
    int n, sum = 0, r;
    cin >> n;
    int temp = n;
    while (n > 0) {
        r = n % 10;
        sum += r * r * r;
        n /= 10;
    }
    cout << "Sum of cube of digits of " << temp << " is " << sum;
}

C++ Output

Input:
456

Output:
Sum of cube of digits of 456 is 405


JAVA Program

import java.util.*;
class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt(), sum = 0, r, temp = n;
        while (n > 0) {
            r = n % 10;
            sum += r * r * r;
            n /= 10;
        }
        System.out.println("Sum of cube of digits of " + temp + " is " + sum);
    }
}

JAVA Output

Input:
789

Output:
Sum of cube of digits of 789 is 1344


Python Program

n = int(input())
temp = n
sum_cubes = 0
while n > 0:
    r = n % 10
    sum_cubes += r ** 3
    n //= 10
print(f"Sum of cube of digits of {temp} is {sum_cubes}")

Python Output

Input:
321

Output:
Sum of cube of digits of 321 is 36


In-Depth Learning – Entire Concept in Paragraphs

Concept Recap

The task is to take an integer, break it into its individual digits, cube each digit, and add those cubes together. If the number is 123, the digits are 1, 2, and 3, and the result is 13+23+33=361^3 + 2^3 + 3^3 = 36. The core idea is digit extraction using modulus to peel off the last digit and integer division to shrink the number until nothing remains.

Gentle Dry Run

Imagine the input is 321. You start with sum = 0. You compute the last digit 321 % 10 = 1, cube it to get 1, add to sum → 1, then shrink the number 321 // 10 = 32. Next digit is 2, cube is 8, sum becomes 9, shrink to 3. Next digit is 3, cube is 27, sum becomes 36, shrink to 0 and stop. The loop ends when the number becomes zero, which guarantees termination.

Real-Life Analogy

Think of a locker with multiple compartments, each compartment holding a token whose value equals the digit printed on its door. Your job is to open each compartment, build a cube whose edge is that token’s value, and then weigh all the cubes together. The final weight is your answer. You always open the last compartment first (the last digit), then move left by discarding the compartment you just processed (integer division), ensuring you won’t miss or repeat any compartment.

Why This Works Mathematically

Every base-10 integer nn can be written as n=di10in = \sum d_i \cdot 10^i, where did_i are digits from 0 to 9. The algorithm replaces the positional weight 10i10^i with a fixed transformation on each digit, here di3d_i^3. Because each did_i is independent and bounded, you can compute di3\sum d_i^3 reliably by repeatedly extracting the least-significant digit with nmod10n \bmod 10. The process is correct because each step handles exactly one digit and strictly reduces nn by a factor of 10, so no digit is skipped or processed twice.

Algorithm Design and Correctness

The loop invariant is that at the start of each iteration, the variable sum equals the sum of cubes of all digits that have already been removed from the original number. The termination condition is n == 0, which must happen because integer division by 10 reduces the number of digits after finitely many steps. Once the loop exits, the invariant implies sum equals the sum of cubes of all digits of the original input.

Complexity Intuition

If the number has dd digits, the loop executes dd times. Each step does constant work: one modulus, one division, one cube (which is just two multiplications), and one addition. That makes the time complexity O(d)O(d), which is also O(log10n)O(\log_{10} n) with respect to the numeric value. Space usage is O(1)O(1) because you only store a handful of integers.

Edge Cases and Input Hygiene

Zero is the simplest case because the loop never runs and the sum remains 0, which equals the sum of the cubes of its single digit 0. Negative inputs need a policy: the common approach is to take the absolute value, compute the sum on the magnitude, and, if you are only printing the sum, ignore the sign. If you need to echo the original input, store it first so you can print it later as shown in the code you ran. Very large inputs fit naturally in Python because integers are arbitrary precision; in C/C++/Java you’ll typically limit inputs to 32- or 64-bit ranges. The sum itself is safe for ordinary inputs because each digit contributes at most 93=7299^3=729, so even a 10-digit number produces at most 7290 as the sum.

Implementation Choices That Matter

Using r*r*r instead of pow(r,3) in C/C++/Java avoids floating-point rounding errors and is faster because it’s just two integer multiplications. Extracting digits arithmetically with % 10 and // 10 is generally more efficient than converting to a string, but the string approach can be nice when you need to keep leading zeros or process non-numeric characters. In languages like Python, both styles are fine; for tight loops in compiled languages, the arithmetic approach is preferred.

Testing Strategy You Can Trust

A good mental test set includes 0, single digits like 7, repeated digits like 999, mixed digits like 1203, and numbers known from related problems like 153 or 370. For example, 999 gives 93+93+93=21879^3+9^3+9^3=2187. The case 1000 gives 13+0+0+0=11^3 + 0 + 0 + 0 = 1, which helps confirm that zeros in the middle are handled correctly. Try symmetric numbers such as 101 or 909 to be sure each zero contributes nothing but still gets processed.

From Sum of Cubes to Armstrong Numbers

This exact computation underlies 3-digit Armstrong numbers (also called Narcissistic numbers of order 3). A 3-digit Armstrong number nn satisfies n=di3n = \sum d_i^3. Famous examples are 153, 370, 371, and 407. Your function already computes di3\sum d_i^3; to check an Armstrong number, compare this sum to the original nn. For general kk-digit Armstrong numbers, the exponent becomes kk rather than 3, which is a powerful extension of the same idea.

Understanding Base and Generalization

The algorithm assumes base-10 only insofar as it divides by 10 and takes modulus 10. If you wanted to do this in another base bb, you would replace 10 with b everywhere. The task “sum of cube of digits” is defined relative to the base representation, so changing the base changes the result because the digit set changes.

Practical Uses in Projects

Even if summing cubes of digits is itself a math puzzle, the technique teaches a reusable pattern for “digit processing”: extract, transform, and aggregate. This pattern appears in checksum validation (like Luhn for card numbers), in digital root computations for numerology-style features, and in compact hashing or scrambling routines where you repeatedly fold digits into a summary value. It also maps well to data parsing tasks where a stream is consumed piece by piece with a running accumulation.

Common Pitfalls and How to Avoid Them

A frequent mistake is forgetting to store a copy of the original number before the loop, which leads to printing the final n as zero. Another is using floating-point pow and then casting back to int, which can introduce rounding surprises. An easy oversight is not handling n == 0, which should yield a sum of 0 and not produce an empty output. Finally, be careful not to use an 8-bit or 16-bit type for the sum; while still unlikely to overflow, sticking to 32- or 64-bit integers is safer and standard.

Interview Talking Points

When explaining this in an interview, emphasize the invariant, termination, and complexity. Mention why integer multiplication is chosen over floating pow, and explain that each iteration processes exactly one digit, so the loop count equals the digit count. If asked for an extension, propose converting this into an Armstrong number checker by comparing the sum to the original or generalizing the exponent to the number of digits for arbitrary-length inputs.

Where to Go Next

Good follow-ups are “Sum of k-th powers of digits,” “Armstrong number check,” “Sum of squares of digits” leading to happy numbers, and “Digital root” which repeatedly sums digits until a single digit remains. Each of these deepens your fluency with modular arithmetic, loops, and stateful accumulation.

SEO-Friendly Wrap-Up

Mastering the sum of cube of digits program builds strong foundations in digit extraction, modular arithmetic, and loop control, which are essential skills for coding interviews and beginner programming courses. By learning how to peel digits with modulus and integer division, cube them efficiently with integer multiplications, and maintain a running total, you gain a pattern you can reuse for Armstrong numbers, digital roots, and validation algorithms. If you’re searching for a clear explanation of the sum of cubes of digits in C, C++, Java, and Python, or how to extend it to Armstrong number checks and related digit problems, this detailed guide gives you the reasoning, test ideas, and best practices needed to write correct, efficient, and interview-ready solutions.