Home > Mobile >  CS50 Week 1 Mario less comfortable. Properly gets input but does nothing after?
CS50 Week 1 Mario less comfortable. Properly gets input but does nothing after?

Time:10-16

I've been stumped on this for hours. My code properly prompts for height but afterwards it does nothing. I've checked everything multiple times and Googled hard. Any help would be appreciated.

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

void build(int n);

int main(void)
{
    int height;

    // Get Height 1-8 or ask again
    do
    {
        height = get_int ("Height: ");
    }
    while (height < 1 || height > 8);
}

void build(int n)
{
    for (int i = 1; i < (n   1); i  )
    {
        for (int j = 1; j < (n   1); j  )
        {
            if (j <= (n - i))
            {
                printf(" ");
            }
            else
            {
                printf("#");
            }
        }
        printf("\n");
    }

}

CodePudding user response:

Your build is a separate function from main. This should be obvious. And this means that whatever's in build does not get invoked.

Call build function after the do-while loop by adding this line: build(height);.

CodePudding user response:

When your program runs, it's the main() function that gets executed. And all that function does is prompt the user to input a number and keep doing these prompts until a number between 1 and 8 is inputted. As soon as that happens, your program ends, and the build() function you wrote never gets called. What you need to do is call it once you have height with build(height).

Alternatively, you can, of course, integrate the code from build() into main() rather than having separate functions. It makes sense in your case since that code only gets executed once; functions are more useful when the same pieces of code are supposed to be executed several times from within main().

CodePudding user response:

As @DannyNiu mentioned you need to call build function in main function. The code goes like this:

#include <conio.h>
#include <stdio.h>

void build(int n);

int main(void)
{
    int height;

    // Get Height 1-8 or ask again
    do
    {
        height = get_int ("Height: ");
        build(height);
    }
    while (height < 1 || height > 8);
}

void build(int n)
{
    for (int i = 1; i < (n   1); i  )
    {
        for (int j = 1; j < (n   1); j  )
        {
            if (j <= (n - i))
            {
                printf(" ");
            }
            else
            {
                printf("#");
            }
        }
        printf("\n");
    }
}
  • Related