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.
Iterative Logic
1. Outer Loop
This loop manages the rows of the triangle. It runs from 1 up to the total number of rows entered by the user.
2. Inner Loop
A nested loop that prints asterisks. The number of asterisks printed depends on the current row index ($j \leq i$).
3. New Line Logic
After the inner loop finishes printing stars for a row, endl is used to move the cursor to the next line.
Key Concepts Learned:
- Nested Loops: Understanding how to place one loop inside another.
- Pattern Recognition: Translating visual shapes into algorithmic logic.
- Dynamic Input: Generating output based on user-defined parameters.
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.
Example C++ Exercise
#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
}
Console Output:
Enter the number of rows for the triangle: 5
*
**
***
****
*****