Given a positive integer n, print a pyramid pattern consisting of stars (*) such that the number of rows equals n. The pyramid should be center-aligned as shown in the example below.
Example:
Input: n = 5
Output:Explanation: Here, the total number of rows is 5, which forms a pyramid structure.
Input: n = 3
Output:Input: n = 7
Output:
Try it on GfG Practice
Using Two Loops - O( n^2) Time and O(1) Space
The idea is to use two nested loops. The outer loop is used to track the rows, while the inner loops are used to print the required spaces and stars for each row.
Illustration:
- For every row
i(from1ton), the pyramid must remain center aligned. - First print spaces, then print stars (
*). - The number of leading spaces for row
iisn - i, which decreases as the row increases. - After spaces, print
2 × i − 1stars. - This pattern makes the pyramid grow symmetrically from the center.
//Driver Code Starts
#include <iostream>
using namespace std;
//Driver Code Ends
void printPyramid(int n) {
// Outer loop for rows
for (int i = 1; i <= n; i++) {
// Print spaces
for (int j = 1; j <= n - i; j++)
cout << " ";
// Print stars
for (int j = 1; j <= 2 * i - 1; j++)
cout << "*";
cout << endl;
}
}
//Driver Code Starts
int main() {
int n = 5;
printPyramid(n);
return 0;
}
//Driver Code Ends
//Driver Code Starts
class GfG {
//Driver Code Ends
static void printPyramid(int n) {
// Outer loop for rows
for (int i = 1; i <= n; i++) {
// Print spaces
for (int j = 1; j <= n - i; j++)
System.out.print(" ");
// Print stars
for (int j = 1; j <= 2 * i - 1; j++)
System.out.print("*");
System.out.println();
}
}
//Driver Code Starts
public static void main(String[] args) {
int n = 5;
printPyramid(n);
}
}
//Driver Code Ends
def print_pyramid(n):
# Outer loop for rows
for i in range(1, n + 1):
# Print spaces
print(" " * (n - i), end="")
# Print stars
print("*" * (2 * i - 1))
#Driver Code Starts
if __name__=="__main__":
n = 5
print_pyramid(n)
#Driver Code Ends
//Driver Code Starts
using System;
class GfG
{
//Driver Code Ends
static void PrintPyramid(int n)
{
for (int i = 1; i <= n; i++)
{
string row = "";
// Spaces
for (int j = 1; j <= n - i; j++)
row += " ";
// Stars
for (int j = 1; j <= 2 * i - 1; j++)
row += "*";
Console.WriteLine(row);
}
}
//Driver Code Starts
static void Main()
{
int n=5;
PrintPyramid(n);
}
}
//Driver Code Ends
function printPyramid(n) {
for (let i = 1; i <= n; i++) {
let row = "";
// Spaces
for (let j = 1; j <= n - i; j++)
row += " ";
// Stars
for (let j = 1; j <= 2 * i - 1; j++)
row += "*";
console.log(row);
}
}
//Driver Code Starts
// Driver code
let n=5;
printPyramid(n);
//Driver Code Ends


