Skip to main content

ProwessApps

Learn · Practice · Excel

Pattern 1

C++ Code Example — Pattern Programs

ADVERTISEMENT

Pattern 1

Objective

Write a C++ program to print a right half pyramid using stars.

Algorithm / Approach

  1. Use an outer loop i from 1 to 5 to handle the rows.
  2. Use an inner loop j from 1 to i to handle the columns.
  3. Print a star "*" inside the inner loop.
  4. Print a newline endl after the inner loop finishes to move to the next row.
main.cpp
#include<iostream>
using namespace std;
int main() {
for(int i = 1; i<=5; i++) {
 for(int j = 1; j<=i; j++) {
  cout<<"*";
 }
 cout<< endl;
}
return 0;
}

Expected Output

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

Explanation of the Program

  • Nested loops are the core of printing 2D patterns.
  • The outer loop controls the vertical rows. The inner loop controls how many characters are printed horizontally on that specific row. Because the inner loop's limit is i, row 1 gets 1 star, row 2 gets 2 stars, etc.

Complexity

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