Thursday, September 10, 2026

Printing Multiplication Table Patterns in C | Conditional Patterns

Integrating conditional arithmetic and structured loops transforms basic multiplication tables into visually appealing numerical grids. Today’s article in our Pattern Programming in C series covers Multiplication Table Patterns. This tutorial demonstrates how to leverage nested loops to render both triangular and grid-based multiplication matrices.

Pattern Title: Triangular Multiplication Table Pattern in C

Purpose: Boost your nested loop logic by generating matrix products dynamically based on row and column index relationships.

Prerequisites: Familiarity with basic for loops, printf, scanf, and standard arithmetic operators.

Final Output

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

2 4 
3 6 9 
4 8 12 16 
5 10 15 20 25 

Deconstructing the Pattern: The Logic

Problem Statement

Write a C program that prompts the user for the number of rows n and prints a triangular grid where the element at row i and column j represents the product of i \times j.

Pattern Analysis & Dynamic Logic

  • Rows (Outer Loop): Control variable i runs from 1 to n (representing the base factor).

  • Columns (Inner Loop): Control variable j runs from 1 to i (representing the multiplier).

  • Cell Calculation: Each printed value is computed dynamically as i * j.

  • Formatting: Proper spacing or tab formatting (\t or %3d) ensures clean visual alignment regardless of single or multi-digit products.

Algorithm

  1. Read the positive integer n from the user.

  2. Execute an outer loop with variable i running from 1 to n.

  3. Execute an inner loop with variable j running from 1 to i.

  4. Compute the product: {val} = i \times j.

  5. Print val formatted with consistent field width for alignment.

  6. Output a newline character (\n) after completing the inner loop to end the row.

Code Implementation

#include <stdio.h>

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;
    }

    // Outer loop for rows (base factor)
    for (int i = 1; i <= n; i++) {
        // Inner loop for columns (multiplier)
        for (int j = 1; j <= i; j++) {
            // Print product of i and j with width formatting for alignment
            printf("%-4d", i * j);
        }
        // Move to the next line after completing the row
        printf("\n");
    }

    return 0;
}

Line-by-Line Code Breakdown

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

  • for (int i = 1; i <= n; i++): Dictates row progression, setting i as the multiplicand.

  • for (int j = 1; j <= i; j++): Controls column generation up to i iterations, setting j as the multiplier.

  • printf("%-4d", i * j);: Multiplies i and j directly and prints the result left-aligned in a 4-character wide field.

  • printf("\n");: Moves the cursor to the next line to complete the triangular shape.

Compiling & Execution

Sample Run

Enter the number of rows: 5
1   
2   4   
3   6   9   
4   8   12  16  
5   10  15  20  25  

Variations & Enhancements

  • Full Matrix Grid: Change the inner loop condition to j <= n to print a full $n \times n$ multiplication grid.

  • Conditional Filter: Apply an if-else block to print products only when they satisfy a condition (e.g., if ((i * j) % 2 == 0)) and print spaces or symbols otherwise.

  • Inverted Triangular Table: Reverse the outer loop (for (int i = n; i >= 1; i--)) to output a descending multiplication triangle.

Common Mistakes & Troubleshooting

  • Alignment Misalignment: Using a plain space (" ") causes grid distortion when products transition from 1-digit to 2-digit numbers. Use width specifiers (e.g., %-4d) or tabs (\t).

  • Confusing Factors: Swapping i * j with arbitrary variables can lead to incorrect sequence outputs.

  • Missing Line Breaks: Omitting printf("\n"); outputs all calculated products onto a single continuous line.

Complexity Analysis

  • Time Complexity: {O}(n^2) — executing n(n+1)/2 total product calculations across nested loops.

  • Space Complexity: {O}(1) — runs in constant memory space.

Mastering grid calculations and output formatting in nested loops builds strong foundational skills for complex multi-dimensional array operations.

Try expanding this code to display only odd multiplication products while hiding even ones! Drop your code in the comments section below.


For all Pattern Programs list click here

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

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