C++ Exercises: Display the pattern like a pyramid using asterisk and each row contain an odd number of asterisks
42. Pyramid Asterisk Pattern with Odd Numbers
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:

For more Practice: Solve these Related Problems:
- Write a C++ program to display a centered pyramid pattern using asterisks, where the number of asterisks in each row is odd and increases by 2 per row.
 - Write a C++ program to print a pyramid of asterisks with odd counts per row, and adjust spacing to center the pattern.
 - Write a C++ program to generate a pyramid using '*' characters such that each row's asterisks follow an odd number sequence, using formatted output.
 - Write a C++ program that reads the number of rows and prints a pyramid pattern of asterisks with each row containing 1, 3, 5, ... asterisks centered.
 
Go to:
PREV : Repeating Number Pyramid.
 NEXT :  Floyd's Triangle.
C++ Code Editor:
Contribute your code and comments through Disqus.
What is the difficulty level of this exercise?
