Try writing down the algorithm in words first, and do it as simple as possible to start with. For example, the following is also a triangle:
*
**
***
****
*****
So, how to print this. What do I need to do?
In the first iteration I need to print one *
In the second iteration I need to print two *
...
In the last iteration I need to print five *
Ok, but what does that mean:
In the first iteration I need to make a call to cout one time, if I place the call to cout in the inner loop that means I only want the inner loop to run once and then exit to the outer loop again.
In the second iteration, then I want the inner loop to run twice in order to make the call to cout twice.
This is where I start sensing a pattern (or maybe after a few steps more):
1:th time for outer loop -> 1 run of the inner loop. 2:nd time for the outer loop -> 2 runs of the inner loop.
This means I can probably use the counter for the outer loop in the condition for the inner loop.
Then try it, and if it does not behave correctly - go back and write down your thoughts step by step again.
1 2 3 4 5 6 7
|
for (int outer = 0; outer < 5; outer++)
{
for(int inner = 0; inner < (outer+1); inner++)
{
cout << '*';
}
}
|
It turns out this code only prints a straight line of *'s. I forgott to include the endl-prints. Where should I put them?
If put it in the inner loop, then there will be a new line before (or after) every print of a *. That's not what I want. So it must be in the outer loop and it should be the last thing I do after printing all the * on the current line. So I should place a call, cout << endl; , just before the outer loop starts a new iteration.
1 2 3 4 5 6 7 8
|
for (int outer = 0; outer < 5; outer++)
{
for(int inner = 0; inner < (outer+1); inner++)
{
cout << '*';
}
cout << endl;
}
|
(I haven't compiled this so I can't say for 100% that it works as I expect)
That's how I think - more or less - when I break down problems, regardless if it is programming or math or whatever. Break it down and put words on what each step should include. Hope it it helps.