0

I spent the past 4 hours working on cs50 pset 1 about the Mario pyramid. I made progress, but I can't figure out what's wrong with my code.

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

int main(void)
{
int s;

    do
    {
        printf("height: ");
        s = GetInt();
    }
    while(s < 0 || s > 23);

    for(int i = 0; i < s; i++)
    {
        for(int i = s - 1; i < s; i++)
        {

            printf(" ");
        }
        for(int i = 1; i + 1 < s; i--)
        { 
            printf("#");
            for(int i = 0; i + 1< s ; i++)
            {
                printf("#");
            }
        }
        printf("\n");

    }
}
1
  • you need 3 variables: 1. hold number of stairs, 2. hold the number of spaces, and 3. hold the number of hashes... as well as i for the loops – Julie Whitehead Jan 21 '15 at 13:53
1

Variables have something called scope. Watch the short on scope for more info!

When you are defining a new variable with the same name as another variable that is in scope, you are practically shadowing the original variable — until the new variable goes out of scope, any reference to this variable using its name will be considered as a reference to the new variable and not the original one.

As for your infinite loop problem, it is likely to be mainly caused by the fact that you are decreasing i by 1 in the following piece of code

for(int i = 1; i + 1 < s; i--)
{ 
    // some code        
}

because obviously if initially i + 1 is less than s and you are decreasing i in each iteration, i will never approach s (although eventually the value of i will wrap around and become greater than or equal to s so this is technically not an infinite loop).

0

as the spification that you have to print 23 line of pyramid, " while(s < 0 || s > 23)" ">23" this could go greater than height of 23, and "< 0" will bring you to infinte loop, it should not be less that 0.

0

You need 3 variables:

  1. hold number of stairs,
  2. hold the number of spaces, and
  3. hold the number of hashes

as well as i for the loops.

0

In your third for loop you decrement i (i.e. i--). This means that your condition, (i + 1) will always be less than s. So off to loop land. Hope this helps.

You must log in to answer this question.

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