C Program to Print Triangle Pattern of Prime Numbers

Here is a C program to print right triangle pattern of prime numbers. Here is a prime number pyramid or triangle pattern of four rows:

C program prime number triangle pattern

Required Knowledge

Algorithm to print right triangle pattern of prime numbers using for loop
This program is similar to right triangle star pattern. The only difference is instead of printing star characters we are printing consecutive prime numbers. I will recommend that, first check how to find a number is prime number or not
  • Take the number of rows(N) of right triangle as input from user using scanf function.
  • Number of integers in Kth row is always K.
  • We will use two for loops to print right triangle of prime numbers.
    • Outer for loop will iterate N time. Each iteration of outer loop will print one row of the pattern.
    • Inner loop will iterate K times. We will first find next prime number using "isPrimeNumber" function and print it. Each iteration of inner loop will print one prime number in current row.

C program to print right triangle pattern of prime numbers

#include<stdio.h>

int isPrimeNumber(int num);
int main() {
   int i, j, rows;
   int counter = 2;
   
   printf("Enter the number of rows\n");
   scanf("%d", &rows);
    
   for (i = 1; i <= rows; i++) {
      for (j = 1; j <= i; j++) {
       /* Try to find next prime number by 
 incrementing counter and testing it for primality */
        while(!isPrimeNumber(counter)){
            counter++;
 }
        printf("%d ", counter);
        counter++;
      }
      printf("\n");
   }
   return(0);
}
 
int isPrimeNumber(int num) {
   int i, isPrime = 1;
   for (i = 2; i <= (num/2); i++) {
      if (num % i == 0){
         isPrime = 0;
         break;
      }
   }
   if (isPrime==1 || num==2)
      return 1;
   else
      return 0;
}
Output
Enter the number of rows
4
2
3 5
7 11 13
17 19 23 29

Related Topics
C program natural number triangle pattern
C program palindrome triangle pattern
C program same row element triangle pattern
C program binary triangle pattern
C program binary rectangle pattern
C program multiplication table triangle pattern
C program heart shape star pattern
C program diamond star pattern
C program diamond star pattern
List of all C pattern programs