Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++
loop
communitycreator

Generate a half pyramid pattern with stars in C++

Vinisha Maheshwari

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

In this shot, we will discuss how to make a half pyramid pattern with stars in C++.

Solution approach

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.

Half Pyramid Pattern

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

Generate a half pyramid pattern using stars in C++

Explanation

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++.

RELATED TAGS

c++
loop
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring