Print a Right-Angled Triangle Star Pattern in C

To print a right-angled triangle star pattern in C, we use nested loops. The outer loop controls the number of rows, and the inner loop prints stars in each row, increasing the count progressively. Below, we will go through multiple examples to illustrate different variations of the right-angled triangle star pattern.


Examples of Right-Angled Triangle Star Patterns

1. Simple Right-Angled Triangle Star Pattern

In this example, we will print a right-angled triangle of stars where the first row contains one star, the second row contains two stars, and so on, forming a triangular shape.

main.c

</>
Copy
#include <stdio.h>

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

    // Outer loop for rows
    for (int i = 1; i <= rows; i++) {
        // Inner loop for printing stars
        for (int j = 1; j <= i; j++) {
            printf("* ");
        }
        printf("\n"); // Move to the next line
    }

    return 0;
}

Explanation:

  1. We define an integer variable rows and set it to 5.
  2. The outer loop runs from i = 1 to rows, controlling the number of rows.
  3. The inner loop runs from j = 1 to i, printing a star for each iteration.
  4. After the inner loop completes, printf("\n") moves to the next line.

Output:

*
* *
* * *
* * * *
* * * * *

2. Upper Right-Angled Triangle Star Pattern

In this example, we will print an upper right-angled triangle where stars are right-aligned. We achieve this by printing spaces before the stars in each row.

main.c

</>
Copy
#include <stdio.h>

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

    // Outer loop for rows
    for (int i = 1; i <= rows; i++) {
        // Inner loop for spaces
        for (int j = 1; j <= rows - i; j++) {
            printf("  "); // Print spaces
        }
        // Inner loop for stars
        for (int j = 1; j <= i; j++) {
            printf("* ");
        }
        printf("\n"); // Move to the next line
    }

    return 0;
}

Explanation:

  1. We define an integer variable rows and set it to 5.
  2. The outer loop (for (int i = 1; i <= rows; i++)) controls the number of rows.
  3. The first inner loop (for (int j = 1; j <= rows - i; j++)) prints spaces before the stars.
  4. The second inner loop (for (int j = 1; j <= i; j++)) prints stars in increasing order.
  5. printf("\n") moves to the next line after each row.

Output:

        * 
      * * 
    * * * 
  * * * * 
* * * * * 

Conclusion

In this tutorial, we covered different ways to print right-angled triangle patterns in C:

  1. Basic Star Triangle: A right-angled triangle using stars.
  2. Number Triangle: Printing numbers instead of stars.
  3. Inverted Triangle: Decreasing the number of stars per row.