Print a Triangle of Asterisks in C++

In this exercise, you will write a C++ program that prints a triangle pattern using asterisks (`*`). This is a common exercise used to practice loops and nested loops. The pattern will consist of a series of rows, with each row containing an increasing number of asterisks.

For example, the pattern for a triangle with 5 rows should look like this:

Enter the number of rows for the triangle: 5
*
**
***
****
*****

Group

Flow Control in C++

Objective

1. Use a loop to iterate through the rows of the triangle.
2. For each row, use a nested loop to print the appropriate number of asterisks.
3. Test the program with different numbers of rows to ensure it works correctly.

Write a program that prints a triangle of asterisks.

Example C++ Exercise

 Copy C++ Code
#include <iostream> // Include the iostream library for input and output

using namespace std; // Use the standard namespace

// Main function - the entry point of the program
int main() {
    int rows; // Variable to store the number of rows for the triangle

    // Ask the user to enter the number of rows for the triangle
    cout << "Enter the number of rows for the triangle: ";
    cin >> rows; // Read the user input and store it in the variable rows

    // Outer loop to handle the number of rows
    for (int i = 1; i <= rows; ++i) {
        // Inner loop to print the asterisks for each row
        for (int j = 1; j <= i; ++j) {
            cout << "*"; // Print an asterisk for the current position
        }
        cout << endl; // Move to the next line after printing all asterisks for this row
    }

    return 0; // Return 0 to indicate that the program executed successfully
}

 Output

Enter the number of rows for the triangle: 5
*
**
***
****
*****

Share this C++ Exercise


More C++ Programming Exercises of Flow Control in C++

Explore our set of C++ Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C++. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C++.