Search code examples
ccs50

CS50 Mario - Less Comfortable - Last Step


I have essentially rounded out the Mario.c assignment for CS50, I am having trouble with the last part of the problem, which is to add an incrementing number of dots'.' before each hash set. I cannot seem to get rid of the last dot, and cannot figure out a solution within my do-while loop that will fix it.

My code so far:

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

    for (int b = 0; b < i; b++)
    {
        int d = i - 1;
        do
        {
            printf(".");
            d--;
        }
        while (d > b);
        
        for (int c = 0; c < b + 1; c++)
        {
            printf("#");
        }

        printf("\n");
    }
}

This returns in the console like this:

.......#
......##
.....###
....####
...#####
..######
.#######
.########

I am simply trying to get rid of the very last dot on the eighth row.

I have tried everything but it remains nonetheless.

Any thoughts/hints?


Solution

  • The problem is you use a do...while loop in for the condition of putting the .'s in place. Don't use a do while loop there. Use a traditional while loop.

    You use a do...while loop when you want to unconditionally perform the loop at least once. You use a while loop when you need to check a condition first.

    In this case however I think you should be using a for loop instead of a while loop but thats a seperate issue.

    Generally you use a while loop when you have no notion in general of how many times it needs to be evaluated and its not straight forward that somethign has to be incremented every single time.

    When you know the bounds of the times the loop needs to operate and your counter has to increase every single time you perform the loop you generally want a for loop.

    In this case: for (int d = i - 1; d < b; d++) { .... }