Prime Number Pyramid

This program prints prime numbers in pyramid form.

Problem Statement

Write a Java program that prints prime numbers in pyramid form up to 4 rows using nested for loop.

Source Code

1 public class PrimePyramid {
2 public static void main(String[] args) {
3 int num = 2;
4 for(int i=1; i<=4; i++) {
5 int count = 0;
6 while(count < i) {
7 boolean prime = true;
8 for(int j=2; j<=num/2; j++) {
9 if(num % j == 0) {
10 prime = false;
11 break;
12 }
13 }
14 if(prime) {
15 System.out.print(num + " ");
16 count++;
17 }
18 num++;
19 }
20 System.out.println();
21 }
22 }
23 }

Program Output

2 
3 5 
7 11 13 
17 19 23 29 

Explanation

The outer loop controls rows, inner logic finds primes sequentially, printing them row by row. Shows how nested loops can generate prime pyramids.

Quick Links to Explore