0

guys I recently start learning programming, and I am stuck an the mario task. I can't find the error. I check it by using "make filename" command on the terminal, and it didn't show any error. However when I run it, it crashed and kept printing spaces forever. What's the error? Thanks for helping! Below is my code:

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

void space1(int h);
void hash(int h);
void space2(int n);


int main(void)
{
    printf("Input the height of the pyramid:");
    int h = get_int();

    if(h > 0 && h <23)
    {
        space1(h);
        hash(h);
        space2(2);
        hash(h);
    }
    else
    {
        printf("Please try again and input h which is within 0 to 23.");
    }
}

void space1(int h)
{
    for(int i = h-1; i < h; i-- )
    {
        printf(" ");
    }
}

void hash(int h)
{
    for(int i = 1; i<=h; i++)
    {
        printf("#");
    }
}

void space2(int n)
{
    for(int i=0; i<n; i++)
    {
        printf(" ");
    }
}
1

You created an (almost) infinite loop within space1. And you need a few more loops.

First, you need to have a loop around the input. As long as the input is invalid (but at least once!), your programme should keep asking for a height.

Then, you need some loop over the lines to print. Within these loops, print the spaces, hashes, spaces, hashes.

Is there any reason why you have two space functions? Both do the same thing, and you could use

Also, let's look at

for(int i = h-1; i < h; i-- )

So i starts at h-1. Condition i < h is true, so the loop executes once. Now, i is decremented to h-2. You see, i < h is clearly true again.

Don't combine i < h and i--. i > h and i-- might make sense, as might i < h and i++, the direction of the increment/decrement should make it possible for the loop to end.

If you have a loop you need to run a specified number of times, and you don't care about the counter variable, both would run exactly n times:

for (int counter = 0; counter < n; counter++)

or

for (int counter = n; counter > 0; counter--)

In both cases, one can instantly see how many iterations this loop is probably going to perform.

Your

for(int i = 1; i<=h; i++)

is an unusual version of the first. Unless you have reasons to count from 1, I'd prefer one of the 0-based versions.

| improve this answer | |

You must log in to answer this question.

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