Sign in to follow this  
Utko

Triangle in C++

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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this