easy
0 views

Pattern Printing-Half Pyramid

Print a half pyramid pattern using asterisks (*) with N rows, where each row contains increasing number of asterisks separated by spaces.

Understand the Problem

Problem Statement

The number of rows N is passed as the input. The program must print the half pyramid using asterisk *.

Constraints

  • 2 ≤ N ≤ 100
  • Each row should contain asterisks separated by single spaces
  • Row i should contain exactly i asterisks

Examples

Example 1
Input
5
Output
*
* *
* * *
* * * *
* * * * *
Explanation

For N=5, we print 5 rows. Row 1 has 1 asterisk, row 2 has 2 asterisks, and so on until row 5 which has 5 asterisks, forming a half pyramid pattern.

Example 2
Input
3
Output
*
* *
* * *
Explanation

For N=3, we print 3 rows. Row 1 has 1 asterisk, row 2 has 2 asterisks, and row 3 has 3 asterisks, creating a smaller half pyramid.

Solution

#include <stdio.h>

int main() {
    int n;
    scanf("%d", &n);
    
    for (int i = 0; i < n; i++) {
        for (int j = 0; j <= i; j++) {
            printf("*");
            if (j < i) {
                printf(" ");
            }
        }
        printf("\n");
    }
    
    return 0;
}
Time:O(N²)
Space:O(1)
Approach:

The C solution uses two nested for loops. The outer loop controls the rows (0 to N-1). The inner loop prints asterisks for the current row. We print an asterisk followed by a space for all but the last asterisk in each row to maintain proper spacing. After each row, we print a newline character to move to the next line.

Visual Explanation

Loading diagram...