Magic Square Pattern (3x3)

This program prints a simple 3x3 magic square using nested for loop.

Problem Statement

Write a Java program that prints a 3x3 magic square using nested for loop.

Source Code

1 public class MagicSquare {
2 public static void main(String[] args) {
3 int[][] square = {
4 {8, 1, 6},
5 {3, 5, 7},
6 {4, 9, 2}
7 };
8 for(int i=0; i<3; i++) {
9 for(int j=0; j<3; j++) {
10 System.out.print(square[i][j] + " ");
11 }
12 System.out.println();
13 }
14 }
15 }

Program Output

8 1 6 
3 5 7 
4 9 2 

Explanation

The program stores a predefined 3x3 magic square in a 2D array and prints it using nested loops. Each row is printed by the inner loop. This demonstrates how nested loops can handle multidimensional arrays and generate structured numeric grids. Shows how nested for loops can print a magic square.

Quick Links to Explore