Skip to main content

ProwessApps

Learn · Practice · Excel

Pattern 2

C++ Code Example — Pattern Programs

ADVERTISEMENT

Pattern 2

Objective

Write a C++ program to print a left half pyramid using stars and spaces.

Algorithm / Approach

  1. Use an outer loop i from 1 to 5.
  2. Use a first inner loop j from 5 down to i to print spaces.
  3. Use a second inner loop k from 1 to i to print stars.
  4. Print a newline.
main.cpp
#include<iostream>
using namespace std;
int main() {
for(int i = 1; i<=5; i++) {
 for(int j = 5; j>=i; j--) {
  cout<<" ";
 }
 for(int k = 1; k<=i; k++) {
  cout<<"* ";
 }
 cout<< endl;
}
return 0;
}

Expected Output

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

Explanation of the Program

  • To push characters to the right side of the screen, we must explicitly print blank spaces before we print the stars.
  • Notice how the space loop counts backward from 5 down to i. This creates an inverse relationship: as the row number increases, the number of spaces decreases, allowing the stars to gradually take up more room.

Complexity

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