Section 1e

Making Programs Easier - Making a Triangle


 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Making a Triangle

Again, it is pretty exciting to see an offset square printed on the screen, but what if you wanted to get really artistic and draw a triangle? Think about how you would do this. It is also worthwhile sketching your ideas on scratch paper. But say you wanted to draw the following picture on the screen.

 

Image of triangle

 

Notice that at the base, the triangle is offset from the left side of the screen by two spaces. Now ask yourself what it would take to print only the first line. One of the primary rules of programming is to never solve big problems. Always break them down into smaller parts. So again, what would it take to print the first line? With the triangle in mind, the first asterisk is two spaces in from the left edge of the triangle, and with the extra offset space in mind, that means you need to print four spaces, then one asterisk, and then end the line.

 

If you notice on the second line, the first asterisk is one space to the left, so you need to print three spaces, then print three asterisks, and then end the line. This is not terribly complex, but it is a pattern. You should then be able to figure out the third line. This is really all there is to programming. Figure out what needs to be done, watch for the patterns that almost always occur, and then solve each small problem that arises one at a time.

 

What is more, if you wrote this out in English or pseudocode first, it was easier for you to figure out what each next step would be. Once again, creating readable programs makes them easier to maintain and diagnose, a characteristic called maintainability, and it makes them easier to improve and add new features, a characteristic called extensibility. And by the way, it will always be easier to program this way; this is how the professionals do it.

Watch this video and write your own triangle-making program using the asterisks.h file from Chapter 1c. Learn from doing these tasks while they are still small.