The pattern has 4 rows, and each row contains stars (*) in a decreasing number:
Row 0: 3 Space 1 star 3 space
Row 1: 2 Space 3 star 2 space
Row 2: 1 Space 5 star 1 space
Row 3: 0 Space 7 star 0 space
Key observation:
The number of spaces decreases with each row, starting from 3 (for row 0) and going down to 0 (for row 3).
The number of star increases with each row, starting from 1 star (for row 0) and going up to 7 star(for row 3).
First Inner Loop (Spaces):
The first inner loop prints the spaces before the number in each row.
The number of spaces in each row is equal to total_rows - row - 1
Second Inner Loop (Stars):
The second inner loop prints the start in each row.
The number of stars in each row increases by 2 for each row.For the i-th row, the number of stars is 2 * i + 1.
Java |
public class Main { public static void main(String[] args) { int total_rows = 5; // Total number of rows in the pyramid // Outer loop for rows for (int row = 0; row < total_rows; row++) { // First inner loop for spaces for (int space = 0; space < total_rows - row - 1; space++) { System.out.print(" "); } // Second inner loop for stars for (int star = 0; star < 2 * row + 1; star++) { System.out.print("*"); } System.out.println(); // Move to the next line } } } |
C++ |
#include <iostream> using namespace std; int main() { int total_rows = 5; // Total number of rows in the pyramid // Outer loop for rows for (int row = 0; row < total_rows; row++) { // First inner loop for spaces for (int space = 0; space < total_rows - row - 1; space++) { cout << " "; } // Second inner loop for stars for (int star = 0; star < 2 * row + 1; star++) { cout << "*"; } cout << endl; // Move to the next line } return 0; } |
Python |
total_rows = 5 # Total number of rows in the pyramid # Outer loop for rows for row in range(total_rows): # First inner loop for spaces for space in range(total_rows - row - 1): print(" ", end="") # Second inner loop for stars for star in range(2 * row + 1): print("*", end="") print() # Move to the next line |