Skip to main content

ProwessApps

Learn · Practice · Excel

Pattern 8

C++ Code Example — Pattern Programs

ADVERTISEMENT

Pattern 8

Objective

Write a C++ program to print a Diamond pattern using stars.

Algorithm / Approach

  1. Use a master loop to build the top half of the diamond (a centered pyramid with 2*i - 1 stars).
  2. Use a second master loop to build the bottom half of the diamond (an inverted centered pyramid).
  3. Carefully align the spaces in both halves so the widest row matches seamlessly.
main.cpp
#include<iostream>
using namespace std;
int main() {
 int n,i,j,k;
 cout<<"Enter the value for N : ";
 cin>>n;
 for(i = 1; i<=n; i++) {
  for(j = 0; j< n-i; j++) {
   cout<<" ";
  }
  for(k=0; k< (2*i)-1; k++) {
   cout<<"*";
  }
  cout<< endl;
 }
 for(i = 1; i< n;i++) {
  for(j = 0; j< i; j++) {
   cout<<" ";
  }
  for(k = 0; k< 2*(n-i)-1; k++) {
   cout<<"*";
  }
  cout<< endl;
 }
return 0;
}

Expected Output

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

Explanation of the Program

  • A diamond is just a standard upward-facing pyramid stacked on top of a downward-facing inverted pyramid.
  • The formula (2 * i) - 1 is a standard mathematical trick used to generate a sequence of odd numbers (1, 3, 5, 7), which ensures the pyramid always has a single star at the very top center.

Complexity

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