Prime Number Grid
This program prints prime numbers in a 3x3 grid.
Problem Statement
Write a Java program that prints first 9 prime numbers in a 3x3 grid using nested for loop.
Source Code
| 1 | public class PrimeGrid { |
| 2 | public static void main(String[] args) { |
| 3 | int num = 2, count = 0; |
| 4 | for(int i=1; i<=3; i++) { |
| 5 | for(int j=1; j<=3; j++) { |
| 6 | while(true) { |
| 7 | boolean prime = true; |
| 8 | for(int k=2; k<=num/2; k++) { |
| 9 | if(num % k == 0) { |
| 10 | prime = false; |
| 11 | break; |
| 12 | } |
| 13 | } |
| 14 | if(prime) { |
| 15 | System.out.print(num + " "); |
| 16 | num++; |
| 17 | break; |
| 18 | } |
| 19 | num++; |
| 20 | } |
| 21 | count++; |
| 22 | } |
| 23 | System.out.println(); |
| 24 | } |
| 25 | } |
| 26 | } |
Program Output
2 3 5 7 11 13 17 19 23
Explanation
The nested loops print primes row by row, checking each number sequentially. This demonstrates prime number grids using nested loops. Shows how nested loops can generate prime number grids.