Print Cubes From 1 to N in Java
Problem
The cube of a number is itself multiplied by itself twice more — printing cubes from 1 to N applies that multiplication to every number in the range.
Given a number N, print the cube of every integer from 1 to N.
Java Program
public class PrintCubes {
public static void main(String[] args) {
int n = 5;
for (int i = 1; i <= n; i++) {
System.out.println(i * i * i);
}
}
}Output
Core Logic
Multiplying each number by itself twice as the loop visits it prints every cube without needing to store any of them.
- 1The loop runs
ifrom1ton, inclusive. - 2At each step,
i * i * icomputes that number's cube directly. - 3The result is printed immediately, before moving on to the next
i.
n = 5, the loop prints 1, 8, 27, 64, 125 — each one i * i * i for i from 1 to 5.Key Point: This is the same shape as printing squares, just with one more multiplication — the loop structure itself never changes.
Why: The loop computes and prints one cube per iteration, and only the loop counter is kept in memory regardless of how large n is.
Key Concepts
Approach 2: Java 8
import java.util.stream.IntStream;
public class PrintCubesStream {
public static void main(String[] args) {
int n = 5;
// Maps each number to its cube, then prints every mapped value
IntStream.rangeClosed(1, n).map(i -> i * i * i).forEach(System.out::println);
}
}
Output
Core Logic
The same cube-and-print sweep can be expressed as a stream pipeline — map each number to its cube, then print the whole stream.
- 1
IntStream.rangeClosed(1, n)generates the numbers 1 through n as a stream. - 2
.map(i -> i * i * i)transforms each number into its cube. - 3
.forEach(System.out::println)prints each cubed value in order.
n = 5, the stream maps 1, 2, 3, 4, 5 to 1, 8, 27, 64, 125 and prints each one.Key Point: map() and forEach() process one number at a time, the same as the loop version — no intermediate collection is ever built.
Why: map() and forEach() process and print one cubed value at a time without ever materializing the full sequence into a collection.