Print a Centered Triangle Number Pattern in C

To print a centered triangle number pattern in C, we use nested loops where the outer loop controls the number of rows, and the inner loops manage spaces for centering and number printing in each row.


Examples of Printing Centered Triangle Number Patterns

1. Simple Centered Triangle Number Pattern

In this example, we print a centered triangle pattern where each row contains increasing odd numbers, aligned in a triangular form.

main.c

</>
Copy
#include <stdio.h>

int main() {
    int rows = 5; // Number of rows in the triangle

    for (int i = 1; i <= rows; i++) {
        // Print spaces for centering
        for (int j = 1; j <= rows - i; j++) {
            printf(" ");
        }

        // Print numbers in the pattern
        for (int j = 1; j <= (2 * i - 1); j++) {
            printf("%d", j);
        }
        
        printf("\n"); // Move to the next line
    }

    return 0;
}

Explanation:

  1. We define an integer variable rows to store the number of rows for the triangle.
  2. The outer loop (i) runs from 1 to rows, determining the number of lines printed.
  3. The first inner loop (j) prints spaces to center the numbers, decreasing in each row.
  4. The second inner loop (j) prints numbers in an increasing pattern up to 2 * i - 1.
  5. The printf("\n") moves the cursor to the next line after printing each row.

Output:

    1
   123
  12345
 1234567
123456789

2. Centered Triangle Number Pattern with Repeating Row Numbers

In this example, instead of printing sequential numbers, we repeat the row number to form a triangle pattern.

main.c

</>
Copy
#include <stdio.h>

int main() {
    int rows = 5;

    for (int i = 1; i <= rows; i++) {
        // Print spaces for centering
        for (int j = 1; j <= rows - i; j++) {
            printf(" ");
        }

        // Print row number multiple times
        for (int j = 1; j <= (2 * i - 1); j++) {
            printf("%d", i);
        }
        
        printf("\n");
    }

    return 0;
}

Explanation:

  1. The variable rows determines the number of rows in the triangle.
  2. The first inner loop prints spaces, making the triangle centered.
  3. The second inner loop prints the row number i multiple times, forming a centered pattern.
  4. Each row follows the rule 2 * i - 1 for the number of elements printed.
  5. The printf("\n") ensures correct line breaks after each row.

Output:

    1
   222
  33333
 4444444
555555555

Conclusion

In this tutorial, we explored different ways to print centered triangle number patterns in C:

  1. Simple Centered Triangle: Printing increasing numbers in each row.
  2. Repeating Row Numbers: Printing the same number in each row.