# Simple loop

• 09-18-2010
Aash
Simple loop
Hello all, i want to display an equilateral triangle.

I thought about it and tried all day but unfortunately didn't do it.
This is so for i've done.

Code:

```for(int i=0; i<5; i++) { for(int j=5; j>i; j--)     for(int k=0; k<i; k++)     cout<<"*";     cout<<" ";     cout<<"\n"; }```
Please let me know where i'm wrong in this loop.

• 09-18-2010
rocketman50
You should give all the for loops curly brackets, even if you don't need to. It makes the code easier to read and helps reduce mistakes.

Also, I think you should be able to do it with only 2 for loops, as it is a 2d shape after all.
• 09-18-2010
Aash
Firstly sorry to everyone, i've posted it twice. There was something wrong with my internet.

@rocketman50: Could you help me out please, I tried it so many times. :(
I'm using three loops becuz i want to make spaces from left too.
• 09-18-2010
rocketman50
Ah I see, you want spaces from the left.

You are very almost there. An easy way to modify your code is to do the following.

First, sort out the brackets

Code:

```        for(int i=0; i<5; i++){                 for(int j=5; j>i; j--){                         cout << " ";                 }                 for(int k=0; k<i; k++){                         cout<<"*";                 }     cout<<"\n"; }```
Then you need to worry about the spacing in-between the stars. A simple IF statement would do. - i.e. if it is the not the first star on the line, add a space before printing a star. So when K is not 0, print out a space before a star.
• 09-19-2010
Aash
I want to get an equilateral triangle , how to do this?? :(
• 09-19-2010
novacain
I find it helps to write a series of comments describing what the function will do, then fill in the code.

__*
_***
*****

Code:

```//start at 1 and loop until equal to the number of lines in the triangle     //determine the number of spaces required     spaces = triangle - line     //determine the number of *     asterisks = ( line * 2 ) - 1     //create the string to write     //for each space           //add a ' ' char to the string     //for each astarisk         //add an '*' to the string     //display the string //end```
Of course this will not work unless you use a fixed pitch font...