C Program to Print Right-Angled Triangle Pattern

🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.

▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube

▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube

Introduction

Printing a right-angled triangle pattern is a simple and common exercise for beginners in C programming. It helps in understanding how to use nested loops and handle formatting.

Problem Statement

Create a C program that:

  • Accepts the number of rows for the triangle.
  • Prints a right-angled triangle using stars (*).

Example:

  • Input: rows = 5
  • Output:
    *
    **
    ***
    ****
    *****
    

Solution Steps

  1. Input the Number of Rows: The size determines how many rows the triangle will have.
  2. Use Nested Loops: The outer loop controls the number of rows, while the inner loop controls the number of stars printed for each row.
  3. Display the Right-Angled Triangle: Print stars in increasing order row by row.

C Program

#include <stdio.h>

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

    // Step 1: Accept the number of rows for the triangle
    printf("Enter the number of rows: ");
    scanf("%d", &rows);

    // Step 2: Outer loop for the rows
    for (i = 1; i <= rows; i++) {
        // Step 3: Inner loop to print stars
        for (j = 1; j <= i; j++) {
            printf("*");
        }

        // Move to the next line after each row
        printf("\n");
    }

    return 0;
}

Explanation

Step 1: Input Number of Rows

  • The program starts by taking input from the user to determine the number of rows for the triangle.

Step 2: Outer Loop for Rows

  • The outer loop controls the number of rows printed. It runs from 1 to the number of rows specified by the user.

Step 3: Inner Loop for Stars

  • The inner loop prints the number of stars (*) in each row. The number of stars printed corresponds to the current row number, increasing by one star for each subsequent row.

Output Example

For rows = 5, the output will be:

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

For rows = 7, the output will be:

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

Conclusion

This C program prints a right-angled triangle using stars (*). The number of stars increases with each row, creating the triangle shape. This exercise is helpful for beginners to practice using loops in C.

My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare