0

I've spend half day reading the site for anything that could help me answer my doubts, but no success. After many tribulations I wrote down a code I thought would finally work but no such luck. It seems like everything I can make up is a block of hashes, with height and base given by the GetInt() function. I've tried for hours to figure out where the mistakes are, but the problem is that I have doubts on many parts of my code.

for (num_line = 0; num_line < height; num_line++)
{
    for (num_spaces = height - 1; (num_spaces <= 0); num_spaces--)
    {
        printf(".");
    }

    for (num_hash = 2; num_hash <= height + 1; num_hash++)
    {
        printf("#");
    }

    printf("\n");
}

For example, I read online that num_hash <= height + 1 is the correct syntax, instead of num_hash = height + 1. Why is that? I declared my variables before the do-while loop, without initializing them. Please, help me solve this program. Why doesn't it print out at all the spaces? And why does the number of hashes on each row remain constant, without starting as two and increment from there?

Sorry if my English is a little bit rusty, it's not my mother language!

1 Answer 1

0

Let's start with your question about num_hash <= height + 1. The reason that you use <= instead of = is this: the test in the for loop must be true on every pass. As soon as it is false, the code drops down to the first line after the for loop. Let's say that you have for(int i=1; i=5; i++) When initialized, i=1 and since 1 does not equal 5, the test is immediately false, so the for loop would never execute it's code. However, if it were <=, the test is true for i = 1 through 5. When it gets to 6, the test goes false and the code then drops to the code below the for loop.

Your basic structure is good. You just need to refine it. You've been basing the number of #s on the overall height of the pyramid. What you may not have figured out is that it isn't based on that, but is based on which line you are printing. Think about that and see how you can limit the number of hashes printed on each line.

You should also take a look at the following:

Tips on spaces and hashes Mario

If this answers your question, please click the check mark to accept this and remove the question from the unanswered pool. Let's keep up on forum maintenance. ;-)

1
  • Thank you! I solved it and feel like I really understood how this program works! It's an exciting feeling! Commented Sep 3, 2015 at 21:16

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .