C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Loop Programs in C

Print Half Pyramid (Right-Angled Triangle)

Introduction

A half pyramid (right-angled triangle) is one of the simplest and most common star patterns.
It consists of stars (*) increasing from one in the first row to n in the last row.

This program uses nested loops to print the right-angled triangle.

 

C Program: Print Half Pyramid (Right-Angled Triangle)

Method 1: Using for loop

C

#include <stdio.h>

 

int main() {

    int n, i, j;

 

    // Input number of rows

    printf("Enter number of rows: ");

    scanf("%d", &n);

 

    // Outer loop for rows

    for (i = 1; i <= n; i++) {

        // Inner loop for stars

        for (j = 1; j <= i; j++) {

            printf("*");

        }

        // Move to next line

        printf("\n");

    }

 

    return 0;

}

Output

 
OUTPUT :
Enter number of rows: 5
*
**
***
****
*****


Explanation

  1. User enters the number of rows (n).
  2. The outer for loop runs from 1 to n to control the rows.
  3. The inner for loop prints stars (*) equal to the row number.
  4. After each row, a newline (\n) moves the cursor to the next line.

 

C Program: Print Half Pyramid (Right-Angled Triangle)

Method 2: Using while loop

C

#include <stdio.h>

 

int main() {

    int n, i = 1, j;

 

    // Input number of rows

    printf("Enter number of rows: ");

    scanf("%d", &n);

 

    // Outer loop for rows

    while (i <= n) {

        j = 1;

 

        // Inner loop for stars

        while (j <= i) {

            printf("*");

            j++;

        }

 

        // Move to next line

        printf("\n");

 

        // Increment row

        i++;

    }

 

    return 0;

}

Output

 
OUTPUT :
Enter number of rows: 5
*
**
***
****
*****


Explanation

  1. User enters the number of rows (n).
  2. The outer for loop runs from 1 to n to control the rows.
  3. The inner for loop prints stars (*) equal to the row number.
  4. After each row, a newline (\n) moves the cursor to the next line.

 

C Program: Print Half Pyramid (Right-Angled Triangle)

Method 3: Using do..while loop

C

#include <stdio.h>

 

int main() {

    int n, i = 1, j;

 

    // Input number of rows

    printf("Enter number of rows: ");

    scanf("%d", &n);

 

    // Outer do...while loop for rows

    do {

        j = 1;

 

        // Inner do...while loop for stars

        do {

            printf("*");

            j++;

        } while (j <= i);

 

        // Move to next line

        printf("\n");

 

        i++; // Increment row

    } while (i <= n);

 

    return 0;

}

Output

 
OUTPUT :
Enter number of rows: 5
*
**
***
****
*****

Explanation

  1. User enters the number of rows (n).
  2. The outer for loop runs from 1 to n to control the rows.
  3. The inner for loop prints stars (*) equal to the row number.
  4. After each row, a newline (\n) moves the cursor to the next line.