Header Ads

C++ Program to Generate Pyramid of Stars

 Algorithm

1. Input:
   - Prompt the user to enter the number of rows (rows).
   - Read and store the input in the variable 'rows'.

2. Outer Loop:
   - For i from 1 to rows:
      3. Inner Loop (Spacing):
         - Initialize space to 1.
         - While space <= rows - i:
            - Output two spaces.
            - Increment space.

      4. Inner Loop (Stars):
         - Initialize k to 0.
         - While k < 2*i - 1:
            - Output an asterisk followed by a space.
            - Increment k.

      5. Output a newline.

6. Output:
   - Continue the outer loop until it reaches rows.

7. End.






Code:

#include <iostream>
using namespace std;

int main()
{
    int space, rows;
    cout << "Enter number of rows: ";
    cin >> rows;

    for (int i = 1, k = 0; i <= rows; ++i, k = 0)
    {
        for (space = 1; space <= rows - i; ++space)
        {
            cout<<"  ";
        }

        while(k != 2*i-1){
            cout<<"* ";
            ++k;
        }
        cout << endl;
    }
    return 0;
}

Explanation:

Here's a breakdown of the code for a program that creates a pyramid of stars based on the user's input for the number of rows.

The program starts by including the Input/Output Stream Library with the "#include <iostream>" line. The "using namespace std;" line simplifies the code by allowing the use of cout and cin without the std:: prefix.

The main function is the entry point of the program. The program declares two integer variables: space, which is for spacing, and rows, which stores the user input for the number of rows.

The program prompts the user to enter the number of rows with "cout << 'Enter a number of rows: ';" and reads the user input with "cin >> rows;". 

The program then uses two nested for loops to create the pyramid. The outer loop initializes and increments the loop variable 'i' from 1 to the number of rows entered by the user. The inner loop (spacing loop) outputs leading spaces before the stars, while the inner loop (stars loop) outputs the stars in the inverted pyramid. The number of stars in each row is controlled by the 'k' variable, which is incremented with each iteration of the stars loop.

Finally, the program outputs a new line to move to the next row of the pyramid with "cout << endl;". The outer loop continues until 'i' reaches the specified number of rows, and the program ends with the "return 0;" statement, indicating successful program execution.

Overall, this program creates a pyramid of stars based on the user's input, using simple input/output operations and loops.


Output:











Related Links:




Post a Comment

0 Comments