2

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;
}
Trev.Drumm
  • 15
  • 2
  • 7
  • 2
    What is your output in your two attempts and how do you want it to be different? – Code-Apprentice Feb 01 '18 at 19:55
  • I am getting a triangle in the first code, which is what I wanted. For the second part of the code, I want it to display a diagonal line of asterisks. I altered the triangle code and tried to play around with it, but can't seem to figure out the right combination to get it to only be a diagonal line. The second code is giving me a half triangle. – Trev.Drumm Feb 01 '18 at 19:58
  • Take a moment to think about what you want to accomplish. Write out the steps to make a diagonal line, for example: 1. Count `i` from 1 to the given number `star`. 2. For each value of `i` print some spaces then a star. On step 2, how many spaces should you print at each row `i`? – Code-Apprentice Feb 01 '18 at 19:59
  • Your second attempt is very close. Remember that you want to only print out a single star (or maybe two, depending on how wide you want the line to be). Otherwise, you need to print spaces. – Code-Apprentice Feb 01 '18 at 20:01

1 Answers1

0

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
}
Phydeaux
  • 2,795
  • 3
  • 17
  • 35