In this shot, we will discuss how to make a half pyramid pattern with stars in C++.
We will use a nested loop to make the half pyramid pattern in C++. A nested loop refers to a loop inside another loop.
Let’s look at an image of the pattern that we will generate.
We will give input as a number
to generate a half pyramid pattern.
We will pass a condition in the outer for
loop, then in the inner for
loop and then print *
as the output. The most important thing that we need to see is the use of endl
.
Let’s look at the code snippet below to understand this better.
#include <iostream>using namespace std;int main() {int number;cin >> number ;for (int i=1; i<=number; i++){for (int j=1; j<=i ; j++){cout << " * ";}cout << endl;}return 0;}
Enter the input below
Please enter a number above to generate an output.
In line 5, we have initialized a variable number
.
In line 6, we take the input as number
.
In line 7, we have initialized an outer for
loop, where we have given a condition to run the loop for number
times.
In line 9, we have initialized an inner for
loop, where we have given conditions to run the loop for i
times.
In line 11, we have given a condition to print *
. It will print for i
times, as given in the condition.
In line 13, we print a next line character. This is done so that the star gets printed now from the next line onwards.
In this way, we can use loops to make a half pyramid pattern in C++.