0

I coded this and it passes. I just want to understand it much better than I do at this moment. I got hung up on a few of things and found the solutions online to those questions I was having but I need help understanding how the code is running. The majority I understand but I have a few lingering questions that I want to get a better grasp of, before I move on.

When I orignally started coding this I was using spaces > 0 in the spaces for loop and it seemed to be adding an additional space before my hashes. For the life of me I couldn't figure out why, but as I was looking through the help section I noticed that the solution was to use spaces > 1 instead. I would like some clarification on why this is.

Also. I had trouble getting the hashes to print out the extra two hashes. I didn't know how to get that to happen. My code was just starting with one hash on the 0 row and increasing from then on but I was short hashes. I found the solution of hashes < (i + 2). I am wondering how this change adds that second hash.

I think I may need a brief explanation on how exactly the computer reads the for loop and prints what it prints. I have a pretty good handle on it, but these questions are tripping me up and keeping me from completely understanding.

I don't want to just pass the tests, I want to have a complete understanding so please help me.

This is my first question so I hope I did a good job explaining my problems.

Thank you

#include <cs50.h>
#include <stdio.h>

int main(void)
{

int height;

do 
{
    printf("Height: ");
    height = get_int();
}
while (0 > height || height > 23);


for (int i = 0; i < height; i++)
{
    for (int spaces = (height-i); spaces > 1; spaces--)
    {
        printf(" ");
    }

    for (int hashes = 0; hashes < (i + 2); hashes++)
    {
        printf("#");
    }
    printf("\n");
}

}

0

A loop

for (int i = 0; i < num; i++)

and a loop

for (int i = num; i > 0; i--)

both iterate num times, since they need num iterations until the condition is false. So in the first row, where i has value 0, you need height-1 spaces and 2 hashes, and for each following row, you need 1 space less, but 1 hash more. So if you like those two common forms, one way would be to use

for (int spaces = height - 1 - i; spaces > 0; spaces--)

or

for (int spaces = 0; spaces < height - 1 - i; spaces++)

and

for (int hashes = i + 2; hashes > 0; hashes--)

or

for (int hashes = 0; hashes < i + 2; hashes++)

You must log in to answer this question.

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