rge5890
rge5890

Reputation: 13

* Triangle Pattern design issue

I am relatively new to programming and am facing a small dilemma, I am trying to print a triangle like this:

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

The idea behind the program is that the user is prompted for the number of rows, so in this example they would have input 5 as the number of rows.

Here is what I have done so far.

#include <iostream>


using namespace std;
int main(){

int i, j, rows;

    printf("Enter the maximum number of stars (between 1 and 10 inclusive):\n");
    scanf("%d",&rows);

    for(i=1; i<=rows; i++)
    {
        for (j=1; j<=10-i; j++) // for space
        printf(" ");

        for(j=1; j<=i; j++)
        {
            printf("*");
        }
        printf("\n");
    }

}

It is close to getting the correct spacing however all the '*' characters start 5 spaces indented.

 _____    *
 _____   **
 _____  ***
 _____ ****
 _____*****

where the _ represents a space, I am not sure how to fix this, I want it to start at the far left hand side of the execution window.

Happy to elaborate on the question if required.

Cheers.

Upvotes: 0

Views: 132

Answers (1)

Jonathan Mee
Jonathan Mee

Reputation: 38959

There are spaces before your input that are generated by the loop:

for (j=1; j<=10-i; j++) // for space
printf(" ");

Note that this loop runs to 10 no matter what is contained in rows.

To fix the code you'd need to make your maximum rows, not the 10 in the loop.

That said, you're using C++, so I'd recommend that you use the language, this is a very simple problem for setw:

int rows;

cin >> rows;

for(auto i = 1; i <= rows; ++i) {
    cout << setw(rows) << string(i, '*') << endl;
}

Live Example

Upvotes: 2

Related Questions