Java ProgramsControl FlowPrint Cubes From 1 to N

Print Cubes From 1 to N in Java

beginner·  Control Flow  ·  Loops

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.

Input
5
Output
1 8 27 64 125

Java Program

Java
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

1 8 27 64 125

Core Logic

Multiplying each number by itself twice as the loop visits it prints every cube without needing to store any of them.

How It Works
  1. 1The loop runs i from 1 to n, inclusive.
  2. 2At each step, i * i * i computes that number's cube directly.
  3. 3The result is printed immediately, before moving on to the next i.
For 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.

Complexity
Time Complexity: O(n)Space Complexity: O(1)

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

for loopmultiplication

Approach 2: Java 8

Java
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

1 8 27 64 125

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.

How It Works
  1. 1IntStream.rangeClosed(1, n) generates the numbers 1 through n as a stream.
  2. 2.map(i -> i * i * i) transforms each number into its cube.
  3. 3.forEach(System.out::println) prints each cubed value in order.
For 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.

Complexity
Time Complexity: O(n)Space Complexity: O(1)

Why: map() and forEach() process and print one cubed value at a time without ever materializing the full sequence into a collection.

Key Concepts

StreamIntStream.rangeClosed()map()

Related Programs