Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to print Pattern 2 * * * * * * * * * * * * * * *

C Code Example — Pattern Programs

ADVERTISEMENT

C Program to print Pattern 2 * * * * * * * * * * * * * * *

Objective

Write a C program to print a right-aligned right triangle of stars.

Algorithm / Approach

  1. Run an outer loop i from 1 to 5.
  2. Run a first inner loop j from 4 down to i to print spaces.
  3. Run a second inner loop j from 1 up to i to print stars.
  4. Print a newline after the inner loops.
main.c
#include<stdio.h>
int main(){
 int i,j;
 for(i=1;i<=5;i++) {
  for(j=4;j>=i;j--) {
   printf(" ");
  }
  for(j=1;j<=i;j++) {
   printf("* ");
  }
 printf("\n");
 }
 return 0;
}

Expected Output

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

Explanation of the Program

  • To push the stars to the right side of the screen, we must print invisible spaces before the stars on every row.
  • As the row number (i) increases, the number of spaces we need to print decreases, while the number of stars increases. This is achieved by running two separate inner loops consecutively inside the outer loop.

Complexity

Time Complexity O(n^2)
Space Complexity O(1)
ADVERTISEMENT