0

I am stuck on cs50 pset1 mario. Here is my code:

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

int main(void)
{
int height;
do
{
    height = get_int();
}
while ( height < 0 || height > 22 );

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

    for (int spaces = 0; spaces < height - 1 - i; i++) //print spaces for 
left pyramid
    {
        printf(" ");
    }

    for (int hashes = 0; hashes <= i+1; i++) // print hashes for left pyramid
   {
       printf("#");
   }

    printf("  "); // print gap

    for (int hashes = 0; hashes <= i+1; i++) // print hashes for right 
pyramid
   {
       printf("#");
   }

    printf("\n"); // print new line

}

}

When I run it it just spams me infinite hashes. How do i fix this?

0

It's an infinite loop, simple enough to fix. Look at the for loop setup:

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

The loop will run until hashes is greater than i+1. The problem is that hashes never changes and i keeps getting larger. Do you see a problem with that?

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

0

Let us try to figure out the pattern here. Like for the left pyramid if the height of the pyramid is 8, check the pattern of spaces and hashes from top to bottom. In this case we need 8 lines, every line has same characters and no of spaces decreases and no of hashes increases from top to bottom.

Now we have the pattern for the left half, the right half is the same, mirror image. So now we can write down the loop as we know the no of spaces and hashes from top to bottom. In programming we need to understand the underlying principle. Plug in the code afterwards becomes easy.

[edit: Code removed]

You must log in to answer this question.

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