0

hello all,
i am trying to make a program using nested for loops that outputs a triangle made of *. so far i have part of the triangle, but am having diffuculty finishing it. my code so far:

#include<iostream> 
#include<conio.h>
using namespace std
void main()
{
      int n = 5;
      char usr = '*'; 
      int x;
      int y;    

       for(y=1;y<=n;y++)
           {
                 for(x=1;x<=y;x++)
                      {
                           cout<<usr;                                                 
                       }
                  cout<<endl;
            }
         getch();
}

it looks like this:
*
**
***
****
*****


but i want it to look like this:
*
**
***
****
*****
****
***
**
*

any help would be appreciated

2
Contributors
3
Replies
6
Views
6 Years
Discussion Span
Last Post by Galf
0

Well, if you want to do it with loops, you just need to reverse your loop and you'll generate the other side of the pyramid. for (y=n-1;y>=1;y--) {...} should generate the other end.

0

i tried that loop i put it right befor getch();
i put:

for (y=n-1;y>=1;y--)
	{
		cout<<usr;
	}

and what i got was:
*
**
***
****
*****
****

0

Correct -- your first attempt was:

for(y=1;y<=n;y++)		// iterate over the number of lines you need to display
{
	for(x=1;x<=y;x++)	// outputs the desired number of '*'s
	{
		...
	}
}

I'm saying you need to reverse that process -- instead of counting 'up' lines, you need to count 'down' now, which is the outer loop I showed. You still need to provide another loop to output the right number of '*'s, though.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.