Public Group

# Triangle in C++

This topic is 3260 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hey guys! I'm having trouble "drawing" a triangle in C++ in the console, just as an exercise, using these characters '*'. Obviously I can't just type it out manually because it is an exercise. I need to use loops and whatnot. Please help =)

##### Share on other sites
What have you tried?

##### Share on other sites
A good start might be Bresenham's line algorithm (:

http://en.wikipedia.org/wiki/Bresenham's_line_algorithm

you can use that to render (or find, then fill) the edges of the triangle

##### Share on other sites
Well, the task was to draw a square, a rectangle and a triangle. I got past the square and the rectangle (though I think my way was quite awkward because I used the modulus operator to check whether it's time to write an std::endl). For the triangle I was thinking of starting with sort of a 6 asterisk square and gradually replace the top ones with spaces, in a loop, so the first line has two spaces on both sides removed, the next has one space on both sides and the last one is just a 6 character row, but I seem to be having trouble implementing this...

P.S. Oh, and if there's a no-homework policy on this website I can assure you that I'm doing all of this on my own. I freakin' wish I was in a CS college, but sadly, my university stuff has absolutely nothing to do with computers :(

##### Share on other sites
What have you tried? Post code.

##### Share on other sites
Quote:
 Obviously I can't just type it out manually because it is an exercise.

Type it out manually first, anyway. That gives you something to look at, so you can figure out what the program result is supposed to look like.

Now, analyze what you have. How many stars are on the first line? The second? Can you form a general rule? How many spaces do you need before the first star on the first line? The first star on the second? Can you form a general rule?

Quote:
 For the triangle I was thinking of starting with sort of a 6 asterisk square and gradually replace the top ones with spaces

The program output doesn't work that way - it's a stream; you can't "go back" to "replace" stuff.

Quote:
 (though I think my way was quite awkward because I used the modulus operator to check whether it's time to write an std::endl)

Try using two separate loops: one to draw the current line, and one that counts up the lines. Then see how that makes the triangle drawing easier to understand as well: drawing the shape consists of drawing each line, and drawing any given line consists of drawing each star in the line.

1. 1
2. 2
3. 3
Rutin
22
4. 4
JoeJ
16
5. 5

• 14
• 29
• 13
• 11
• 11
• ### Forum Statistics

• Total Topics
631774
• Total Posts
3002290
×