w3resource

C++ Exercises: Display the pattern like a pyramid using asterisk and each row contain an odd number of asterisks

C++: For Loop Exercise-42 with Solution

Write a C++ program that displays the pattern like a pyramid using asterisks, with odd numbers in each row.

Sample Solution:

C++ Code :

#include <iostream> // Include the input/output stream library
using namespace std; // Using standard namespace

int main() // Main function where the execution of the program starts
{
    int i, j, n; // Declare integer variables i, j, and n

    // Display message asking for input
    cout << "\n\n Display such a pattern like a pyramid containing odd number of asterisk in each row:\n";
    cout << "-----------------------------------------------------------------------------------------\n";
    cout << " Input number of rows: ";
    cin >> n; // Read input for the number of rows from the user

    // Loop to print the pyramid pattern containing odd numbers of asterisks in each row
    for (i = 0; i < n; i++) // Loop for the number of rows
    {
        for (j = 1; j <= n - i; j++) // Loop to print spaces before the asterisks
        {
            cout << " "; // Print a space
        }

        for (j = 1; j <= 2 * i - 1; j++) // Loop to print asterisks in each row
        {
            cout << "*"; // Print an asterisk
        }

        cout << endl; // Move to the next line after each row is printed
    }
}

Sample Output:

 Display such a pattern like a pyramid containing odd number of asterisk in each row:                                                         
-----------------------------------------------------------------------------------------                                                     
 Input number of rows: 5                                               
                                                                       
    *                                                                  
   ***                                                                 
  *****                                                                
 ******* 

Flowchart:

Flowchart: Display the pattern like a pyramid using asterisk and each row contain an odd number of asterisks

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a program in C++ to make such a pattern like a pyramid using number and a number will repeat for a row.
Next: Write a program in C++ to print the Floyd's Triangle.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/cpp-exercises/for-loop/cpp-for-loop-exercise-42.php