Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to print Pattern 8 * *** ***** *** *

C Code Example — Pattern Programs

ADVERTISEMENT

C Program to print Pattern 8 * *** ***** *** *

Objective

Write a C program to print a Diamond pattern of stars.

Algorithm / Approach

  1. A diamond is just a regular pyramid placed on top of an inverted pyramid.
  2. Top half: Loop i from 1 to n. Print spaces (decreasing), then print stars (2*i - 1).
  3. Bottom half: Reset space counter. Loop i from 1 to n-1. Print spaces (increasing), then print stars (2*(n-i) - 1).
main.c
#include<stdio.h>
int main( ) {
 int i, j,n,space;
 scanf("%d",&n);
 space = n-1;
 for(i=1; i<=n;i++) {
  for(j=1; j<=space; j++) {
   printf(" ");
  }
  space--;
  for(j=1; j<=2*i-1; j++) {
   printf("*");
  }
  printf("\n");
 }
 space = 1;
 for(i=1; i < n;i++) {
  for(j=1; j<=space; j++) {
   printf(" ");
  }
  space++;
  for(j=1; j <=2*(n-i)-1; j++) {
   printf("*");
  }
  printf("\n");
 }
 return 0;
}

Expected Output

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

Explanation of the Program

  • The formula 2 * i - 1 is standard for generating odd numbers (1, 3, 5, 7). This ensures the pyramid has a single star at the peak and grows symmetrically by 2 stars on each subsequent row.
  • To build the diamond, we literally just write the code for a right-side-up pyramid, and then immediately paste the code for an upside-down pyramid directly below it.

Complexity

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