Pattern 1
Objective
Write a C++ program to print a right half pyramid using stars.
Algorithm / Approach
- Use an outer loop
ifrom 1 to 5 to handle the rows. - Use an inner loop
jfrom 1 toito handle the columns. - Print a star
"*"inside the inner loop. - Print a newline
endlafter 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)