I am trying to output a number of lines, given by the user, of stars shaped as a triangle below:

*********
          *******
           *****
            ***
             *

i have got the following code:

void line (int n, char c)
{

  for (int i = 1;i <= n; i++)
    {
      for (int m = 0 ;m <= n-i; m++)

      for (int s=0; s <= m; s++)

          cout << c ;

          cout << endl;
    }
}


int main()

{
 
  int n = 0;
  cout << "Enter number of lines: ";
  cin >> n;
  line (n,'*');
}

but it print out the stars in the following format:

*********
*******
*****
***
*

Any help will be appreciated. Thank you :)

but it print out the stars in the following format:

*********
*******
*****
***
*

For me, it prints this:

***************
**********
******
***
*

Why do I point out the distinction? Because the first line has 5 more * than the line below it;
that line has 4 more than the line below it;
that line has 3 more than the line below it;
and that line has 2 more than the one below it.

There's a pattern there. And what you need are some spaces at the beginning, so you'll need to be outputting the space character somewhere. The number of leading spaces changes each row, so it's likely that outputting a space will be in a loop.

Thank you Dave. that is what my teacher told me as well.
i am quite new to c++.
where exactly do i include the spaces? how will the loops will look like?

cheers

This is not real code, but just an example. You want to loop through a number of spaces before you loop through the number of stars, So...

void line (int n, char c)
{
   for ( int i = 1;i <= n; i++ )
   {
         for ( /* */; /* */; /* */ )
         {
            cout << ' ';
         }
         for ( int s=0; s <= m; s++ )
         {
            cout << c ;
         }
      cout << endl;
   }
}

By the way, especially since you are new always use full bracing. And try to always use good indentation as well.

[edit]Using pencil and paper (or whatever your favorite writing utensil), make a table that lists each row, the number of leading spaces in that row, and and the number of stars in that row. Watch a pattern emerge to tell you how to put your for loops together.

Thank you Dave. that is what my teacher told me as well.
i am quite new to c++.
where exactly do i include the spaces? how will the loops will look like?

cheers

Being new to C++ is not a factor here. Write down a Grid in paper. Any number of squares is okay as long as it is up to the requirements. Find out the numercial pattern, find the positions of the spaces and then convert it to variables. In short, write down an algorithm or pseudocode in plain English. This will not change with the language. Then start coding.

This article has been dead for over six months. Start a new discussion instead.