Concentric Number Square
This program prints concentric squares with numbers.
Problem Statement
Write a Java program that prints concentric number squares in a 5x5 grid.
Source Code
| 1 | public class ConcentricNumberSquare { |
| 2 | public static void main(String[] args) { |
| 3 | int n = 5; |
| 4 | for(int i=0; i<n; i++) { |
| 5 | for(int j=0; j<n; j++) { |
| 6 | int min = Math.min(Math.min(i, j), Math.min(n-1-i, n-1-j)); |
| 7 | System.out.print((min+1) + " "); |
| 8 | } |
| 9 | System.out.println(); |
| 10 | } |
| 11 | } |
| 12 | } |
Program Output
1 1 1 1 1 1 2 2 2 1 1 2 3 2 1 1 2 2 2 1 1 1 1 1 1
Explanation
The variable min computes the shortest distance of each cell from any border, and printing min+1 produces concentric numeric layers, demonstrating mathematical distance-based logic within nested loops.