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
Show 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
*
**
***
****
*****