Wednesday, September 9, 2026

Printing Prime Number Patterns in C | Conditional Patterns

Integrating algorithmic checks into nested loops elevates basic pattern programming into advanced problem-solving. Today’s article in our Pattern Programming in C series covers the Prime Number Triangle Pattern. This tutorial demonstrates how to combine nested loop structures with primality testing logic to display prime numbers in a triangular arrangement.

Pattern Title: Prime Number Right Triangle Pattern in C

Purpose: Strengthen your nested loop logic, conditional reasoning, and prime-checking algorithms.

Prerequisites: Knowledge of basic for loops, printf, scanf, custom functions, and if-else control flow.

Final Output

For an input of rows = 4, the program generates:

2
3 5
7 11 13
17 19 23 29

Deconstructing the Pattern: The Logic

Problem Statement

Write a C program that prompts the user for the number of rows n and prints a right-angled triangle containing sequential prime numbers. Row 1 contains 1 prime number, Row 2 contains 2, Row 3 contains 3, and so on.

Pattern Analysis & Logic

  • Rows (Outer Loop): i runs from 1 to n.

  • Columns (Inner Loop): j runs from 1 to i, dictating how many prime numbers to display in the current row.

  • Primality Check: A positive integer greater than 1 is prime if it has no positive divisors other than 1 and itself. We maintain a global candidate integer starting at 2 and increment it until we find the next prime value to print.

Step-by-Step Algorithm

  1. Read the total number of rows n from the user.

  2. Initialize a candidate number variable num = 2.

  3. Execute an outer loop i from 1 to n.

  4. Execute an inner loop j from 1 to i.

  5. Within the inner loop, continuously test num using a primality check algorithm:

    • If num is prime, print num followed by a space, increment num, and move to the next column j.

    • If num is not prime, increment num and recheck until a valid prime is found.

  6. Print a newline character (\n) after completing each row.

Code Implementation

#include <stdio.h>
#include <stdbool.h>

// Helper function to check if a number is prime
bool isPrime(int num) {
    if (num <= 1) return false;
    for (int k = 2; k * k <= num; k++) {
        if (num % k == 0) return false;
    }
    return true;
}

int main() {
    int n;

    // Prompt user for input
    printf("Enter the number of rows: ");
    if (scanf("%d", &n) != 1 || n <= 0) {
        printf("Please enter a valid positive integer.\n");
        return 1;
    }

    int currentNum = 2;

    // Outer loop for rows
    for (int i = 1; i <= n; i++) {
        // Inner loop for columns in row 'i'
        for (int j = 1; j <= i; j++) {
            // Find the next prime number
            while (!isPrime(currentNum)) {
                currentNum++;
            }
            // Print the valid prime number
            printf("%d ", currentNum);
            currentNum++;
        }
        // Move to the next line after completing the row
        printf("\n");
    }

    return 0;
}

Line-by-Line Code Breakdown

  • bool isPrime(int num): A helper function that returns true if num is prime and false otherwise, optimizing checks up to sqrt{num}.

  • if (scanf("%d", &n) != 1 || n <= 0): Performs strict input validation to guard against non-numeric or non-positive input values.

  • int currentNum = 2;: Tracks the continuous sequence of integers, starting from the first prime number 2.

  • while (!isPrime(currentNum)) { currentNum++; }: Skips non-prime numbers until the next prime integer is found.

  • printf("%d ", currentNum); currentNum++;: Prints the identified prime number and increments the candidate tracker for subsequent iterations.

  • printf("\n");: Terminates the current row line.

Compiling & Execution

Sample Run

Enter the number of rows: 5
2 
3 5 
7 11 13 
17 19 23 29 
31 37 41 43 47 

Variations & Enhancements

  • Inverted Prime Triangle: Reverse the outer loop (for (int i = n; i >= 1; i--)) to print the largest row of prime numbers at the top.

  • Conditional Primality Filtering: Print numbers from a standard counter, but display non-prime positions as symbols (e.g., *).

  • Centered Pyramid: Add space-printing logic before the inner number loop to convert the right-angled triangle into a centered pyramid.

Common Mistakes & Troubleshooting

  • Forgetting to Increment currentNum After Printing: If currentNum is not incremented after printing, the while loop will repeatedly find and print the exact same prime number.

  • Unoptimized Primality Checks: Testing factors up to num - 1 rather than $\sqrt{\text{num}}$ significantly degrades performance for larger row counts.

  • Treating 1 as Prime: Ensure your prime validation logic explicitly excludes 1, as 1 is neither prime nor composite.

Complexity Analysis

  • Time Complexity: {O}(k \sqrt{m})$, where k is the total count of printed numbers (n(n+1)/2) and m is the value of the largest prime printed.

  • Space Complexity: {O}(1) — operates in constant auxiliary space.

Combining algorithmic checks like primality testing with nested loops provides a solid foundation for mastering dynamic matrix operations.

Try modifying the code to create an Inverted Prime Triangle! Post your solution in the comments section below.



For all Pattern Programs list click here

…till the next post, bye-bye & take care