0

I have been struggling with pset1: creating a pyramid for a long time. I am reading other people's codes to learn the logic but I still cannot understand what is going on. Would you please explain the codes (starting from the "while" statement") in text?? Thank you!!

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

int main(void)
{
    int height;
    do
    {
        height = get_int("Height: ");
    }
    while (height < 1 || height > 8);

    for (int i = 0; i <= height ; i++)
    {

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

        printf("\n");
    }
}
0
  1. when you are doing this -> for (int i = 0; i <= height ; i++) <- count how many times you are iterating. is it equal to the height or more than height?

  2. Then do the same for this. -> for (int spaces = 0; spaces < height - i; spaces++)

  3. finally here -> for (int j = 0; j < i; j++) <- consider i = 0. When i = 0, we want one # to be printed but in your condition because j = 0 and j < i, no # would print.

I would suggest take a paper and pen and see how you want the pyramid to look like and how your commands are making it look like.

If you have doubts please feel free to ask. I or someon else in the forum would definitely help you. Have a great day!! :)

2
  • Hi Himanshi, thank you for answering my question! The first for loop >> for (int i = 0; i <= height; i++) << is determining the number of rows, am i correct?? And I guess the 2 inner for loops are for columns but how does the system know how many columns should be printed?? – maggiechan Aug 11 '20 at 8:13
  • you count from zero. Whatever initial value you are giving to i, system will count from there. suppose height = 2. and i = 0. So now when you count in the for loop, system will print till your second condition of for loop. in this example, acc to your condition, i = 0, i = 1, i = 2,.. here now if i add 1 once more to i, the condition is defied so the system would stop. but You count how many rows would be printed. 0, 1, and 2.. thats 3 rows. but you only wanted 2. Right? – Himanshi Aug 11 '20 at 11:52

You must log in to answer this question.

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