KnowledgeBoat Logo

Java Pattern Programs

Write a program in Java to display the following pattern:

                2
            3   5    
        7   11  13
    17  19  23  29
31  37  41  43  47

Java

Java Nested for Loops

ICSE

1 Like

Answer

public class KboatPattern
{
    public static void main(String args[]) {
        int x = 2;
        for (int i = 1; i <= 5; i++) {
            for (int j = 5; j > i; j--) {
                System.out.print("\t");
            }
            for (int k = 1; k <= i; k++) {
                System.out.print(x + "\t");
                for (int l = x + 1; l < 1000; l++) {
                    boolean isPrime = true;
                    for (int m = 2; m <= l / 2; m++) {
                        if (l % m == 0) {
                            isPrime = false;
                            break;
                        }
                    }
                    if (isPrime) {
                        x = l;
                        break;
                    }
                }
            }
            System.out.println();
        }
    }
}

Output

BlueJ output of Write a program in Java to display the following pattern: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

Answered By

2 Likes