Java ProgramsControl FlowPrint Squares From 1 to N

Print Squares From 1 to N in Java

beginner·  Control Flow  ·  Loops

Problem

The square of a number is itself multiplied by itself — printing squares from 1 to N just applies that one multiplication to every number in the range.

Given a number N, print the square of every integer from 1 to N.

Input
6
Output
1 4 9 16 25 36

Java Program

Java
public class PrintSquares { public static void main(String[] args) { int n = 6; for (int i = 1; i <= n; i++) { System.out.println(i * i); } } }

Output

1 4 9 16 25 36

Core Logic

Multiplying each number by itself as the loop visits it prints every square 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 computes that number's square directly.
  3. 3The result is printed immediately, before moving on to the next i.
For n = 6, the loop prints 1, 4, 9, 16, 25, 36 — each one i * i for i from 1 to 6.
💡

Key Point: Nothing needs to be stored here — each square is computed and printed in the same step, so memory use never grows with n.

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

Why: The loop computes and prints one square 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 PrintSquaresStream { public static void main(String[] args) { int n = 6; // Maps each number to its square, then prints every mapped value IntStream.rangeClosed(1, n).map(i -> i * i).forEach(System.out::println); } }

Output

1 4 9 16 25 36

Core Logic

The same square-and-print sweep can be expressed as a stream pipeline — map each number to its square, 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) transforms each number into its square.
  3. 3.forEach(System.out::println) prints each squared value in order.
For n = 6, the stream maps 1, 2, 3, 4, 5, 6 to 1, 4, 9, 16, 25, 36 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 squared value at a time without ever materializing the full sequence into a collection.

Key Concepts

StreamIntStream.rangeClosed()map()

Related Programs