Create a triangle type pattern
Write a C++ program that asks the user to enter a number of rows to be printed. It should then display for the first row one asterisk preceded by periods. The second row should display two asterisks preceded by periods and so on until all the rows have been printed as entered by the user.
A sample run would be like so:
....*
...**
..***
.****
*****
I've seen many varied questions surrounding this particular problem.
Here's a solution, firstly, just the logic of the code for clarity, not concerning ourselves with error trapping incorrect keyboard input. The object is to understand the reasoning of the logic of addressing the problem at hand.
// 29 Nov, 2007.
#include <iostream>
using namespace std;
int main()
{
int rows, c;
cout << "Enter the number of rows: ";
cin >> rows;
cin.get();
for (int r = 1; r <= rows; r++)
{
for (c = 1; c <= rows - r; c++)
cout << ".";
for (; c <= rows; c++)
cout << "*";
cout << endl;
}
// exit routine
cout << "\n\n...Press 'ENTER' key to EXIT...\n";
cin.get();
return 0;
}
Copy and paste the above into your compiler of choice, compile and run it. As you can see, it works.
The guts of the solution is that an outer loop is first created, that relating to the rows. Within this loop the columns are accounted for and for this particular problem the columns loop is split into two, one dealing with the periods and the other dealing with the asterisks. Now trying to explain the sequence of the variables concerned will take forever. I reckon the code alone should clearly explain what is happening.
I mentioned earlier that this code doesn't account for incorrect data input, try it, enter a non numeric for the number of rows. The program doesn't work.
The following pages discuss enhancements to the program.


Recent comments
1 week 3 days ago
2 weeks 4 days ago
3 weeks 2 days ago
3 weeks 4 days ago
12 weeks 5 days ago
28 weeks 1 day ago
28 weeks 2 days ago
29 weeks 6 days ago
29 weeks 6 days ago
29 weeks 6 days ago