Search code examples
c++user-inputshapesdiagonal

Creating a diagonal line of stars that the user has defined in C++


I am having to write some code that needs to create a diagonal line of asterisks. I know how to write code that outputs a triangle:

cout<<"What size of stars would you like to draw? ";
cin>>star;

int space;
for(int i = 1, k = 0; i <= star; I++, k = 0)
{
    for(space = 1; space <= star-i; space++)
    {
        cout <<"  ";
    }

    while(k != 2*i-1)
    {
        cout << "* ";
        k++;
    }
    cout << endl;

And I altered that code to create a half triangle from it, I just can't seem to find how to get it to only be a diagonal line. Here is what I have for the half triangle:

for(int i = 1, k = 0; i <= star; i++, k = 0) {
    while(k != 2*i-1) {
        cout << "* ";
        k++;
    }
    cout << endl;
}

Solution

  • Just think of the diagonal line as being a half triangle filled with empty space :-).

    for(int i = 1, k = 0; i <= star; i++, k = 0) {
        while(k != 2*i-1) {
            cout << "  ";    // print whitespace until the end of the row
            k++;
        }
        cout << "*" << endl; // print a dot at the end
    }