C Program to Print an Inverted Right Triangle Star Pattern

1. Introduction

Creating patterns with C programming is a foundational skill that demonstrates the power of loops and conditional statements. In this guide, we'll explore how to generate a left-aligned triangle star pattern. This pattern is characterized by its alignment against the left margin, making it a visually distinct form of the traditional right-aligned triangle pattern.

2. Program Steps

1. Prompt the user to enter the number of rows for the triangle pattern.

2. Use a for loop to iterate through each row.

3. Within each row iteration, implement two inner loops: one for printing spaces and another for printing stars, ensuring the triangle aligns to the left.

3. Code Program

#include <stdio.h>

int main() {
    int rows, i, j;

    // User input for number of rows
    printf("Enter the number of rows: ");
    scanf("%d", &rows);

    for(i = 1; i <= rows; i++) {
        // Loop for printing spaces
        for(j = 1; j <= rows - i; j++) {
            printf(" ");
        }
        // Loop for printing stars
        for(j = 1; j <= i; j++) {
            printf("*");
        }
        printf("\n");
    }

    return 0;
}

Output:

Enter the number of rows: 5
    *
   **
  ***
 ****
*****

Explanation:

1. The program begins by including the stdio.h header, necessary for input and output operations.

2. Within the main function, integer variables rows, i, and j are declared for storing the number of rows and for loop control.

3. The user is prompted to enter the desired number of rows for the triangle pattern.

4. A for loop iterates through each row from 1 to the number of rows entered by the user.

5. Inside the first loop, a nested loop prints the required number of spaces to ensure the stars align to the left. As i increases, the number of spaces decreases, making the stars align to the left edge.

6. Another loop within the first prints the stars. The number of stars increases with each row, forming the left-aligned triangle pattern.

7. After completing each row's printing, a newline character is printed to move to the start of the next line.

8. The program concludes with return 0;, indicating successful execution.


Comments