1

This is what check50 gives me:

>     :( handles a height of 1 correctly
>         expected ""#  #"", not ""   "\n"#  #""
>     :( handles a height of 2 correctly
>         expected "" #  #"\n"##  ...", not ""    "\n" #  #..."
>     :( handles a height of 8 correctly
>         expected ""       #  #"\...", not ""          "\n..."
>     :( rejects a height of 9, and then accepts a height of 2
>         expected "" #  #"\n"##  ...", not ""    "\n" #  #..."

and this is my code, which I replaced all the whitespaces with periods (".") for debug.

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

int main(void)
{

    // defining variables
    int height;
    int spaces;
    int row;
    int hashes;

    do
    {
        //prompt user for height
        height = get_int("Height: ");
    }
    // prompts user again if height is less then 1 or larger then 8
    while (height < 1 || height > 8);


    for (row = 0; row <= height; row++)
    {
        // repeteadly prints leading spaces
        for (spaces = 1; spaces <= height - row; spaces++)
        {
            // prints one space, to be repeated
            printf(".");
        }

        // repeatedly prints left hashes
        for (hashes = 0; hashes <= height - spaces; hashes++)
        {

            // print hash, to be repeated
            printf("#");
        }

        //print two spaces as seperators
        printf("..");

        // repeatedly prints right hashes
        for (hashes = 0; hashes <= height - spaces; hashes++)
        {
            // print hash, to be repeated
            printf("#");

        }

        //print newline for next row
        printf("\n");

    }
}

compiling and running the program with an input height of 8 gives me this output, which shows that the problem comes from unwanted spaces on the line directly below the input line. Where the spaces are added, I can't figure out:

~/pset1/mario/ $ ./mario
Height: 8
..........
.......#..#
......##..##
.....###..###
....####..####
...#####..#####
..######..######
.#######..#######
########..########

2 Answers 2

5

What conclusion can be drawn from these two facts?

  • This loop for (row = 0; row <= height; row++) will generate height + 1 lines of output (0 through height inclusive)
  • The first output line (ie row = 0) is incorrect.

Technically,when row is 0, the spaces loop executes height times, and spaces is height + 1 when done, therefore the hashes loops executes 0 times.

3

You want to repeat your outer loop one less time and print one less space each time. To do this you simply need to change your <= operator in your outer loop and your first space printing loop a <

You must log in to answer this question.

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