Numeric Pyramid with Squares

This program prints a pyramid of squares using nested for loop.

Problem Statement

Write a Java program that prints a pyramid of squares up to 4 rows using nested for loop.

Source Code

1 public class SquarePyramid {
2 public static void main(String[] args) {
3 int num = 1;
4 for(int i=1; i<=4; i++) {
5 for(int j=1; j<=i; j++) {
6 System.out.print((num*num) + " ");
7 num++;
8 }
9 System.out.println();
10 }
11 }
12 }

Program Output

1 
4 9 
16 25 36 
49 64 81 100 

Explanation

The outer loop controls rows, inner loop prints squares of sequential numbers. This demonstrates how nested loops can generate pyramids of squared values. Shows how nested for loops can generate square pyramids.

Quick Links to Explore