C Program to Print a Right Triangle Star Pattern

1. Introduction

In this post, we're going to learn how to create a simple yet fundamental pattern in C programming: the right triangle star pattern. This pattern is excellent for beginners to grasp the concept of loops and how they can be used to generate patterns in programming.

2. Program Steps

1. Ask the user to enter the number of rows for the triangle.

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

3. Inside the loop, use another for loop to print stars (*) in each row, increasing the number of stars in each subsequent row.

3. Code Program

#include <stdio.h>

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

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

    for(i = 1; i <= rows; i++) {
        // Nested loop to print stars
        for(j = 1; j <= i; j++) {
            printf("*");
        }
        // Move to the next line after each row is printed
        printf("\n");
    }

    return 0;
}

Output:

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

Explanation:

1. The program begins with including the stdio.h library for input and output functions.

2. The main function is declared, which is the entry point of a C program.

3. Three integer variables rows, i, and j are declared for storing the number of rows and for loop iteration, respectively.

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

5. A for loop is used to iterate from 1 to the entered number of rows. This loop handles the rows of the triangle.

6. Inside the first loop, a nested loop prints the stars in each row. The number of stars increases with each iteration of the outer loop, creating the right triangle pattern.

7. After printing the stars for a row, the program prints a newline character (\n) to move to the next row.

8. The program ends with return 0;, signaling successful execution.


Comments