Print Squares From 1 to N in Java
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.
Java Program
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
Core Logic
Multiplying each number by itself as the loop visits it prints every square without needing to store any of them.
- 1The loop runs
ifrom1ton, inclusive. - 2At each step,
i * icomputes that number's square directly. - 3The result is printed immediately, before moving on to the next
i.
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.
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
Approach 2: Java 8
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
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.
- 1
IntStream.rangeClosed(1, n)generates the numbers 1 through n as a stream. - 2
.map(i -> i * i)transforms each number into its square. - 3
.forEach(System.out::println)prints each squared value in order.
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.
Why: map() and forEach() process and print one squared value at a time without ever materializing the full sequence into a collection.