Integrating algorithmic checks into nested loops elevates basic pattern programming into advanced problem-solving
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
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
Pattern Analysis & Logic
Rows (Outer Loop):
iruns from1ton. Columns (Inner Loop):
jruns from1toi, 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 2and increment it until we find the next prime value to print.
Step-by-Step Algorithm
Read the total number of rows
nfrom the user. Initialize a candidate number variable
num = 2. Execute an outer loop
ifrom1ton. Execute an inner loop
jfrom1toi. Within the inner loop, continuously test
numusing a primality check algorithm:If
numis prime, printnumfollowed by a space, incrementnum, and move to the next columnj. If
numis not prime, incrementnumand recheck until a valid prime is found.
Print a newline character (
\n) after completing each row.
Code Implementation
#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 returnstrueifnumis prime andfalseotherwise, 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 number2. 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
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
currentNumAfter Printing: IfcurrentNumis not incremented after printing, thewhileloop will repeatedly find and print the exact same prime number. Unoptimized Primality Checks: Testing factors up to
num - 1rather than $\sqrt{\text{num}}$ significantly degrades performance for larger row counts. Treating 1 as Prime: Ensure your prime validation logic explicitly excludes
1, as1is 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