CS50 PSet 1: Mario

A guide to the more difficult version of the ‘Mario’ problem in CS50 Week 1.

Goal: To write a program in C that outputs a pyramid of blocks (using the # symbol) of a given size, with a gap in the middle.

For example, if the user were to enter 4, the outputted pyramid would look like the below:

   #  #
## ##
### ###
#### ####

The script must prompt the user for an integer and only accept values between 1 and 8, continuing to ask until a suitable integer is entered.

The first step is to ask the user for the height of the pyramid using the get_int() function defined within the cs50 library. I’ve used a do while loop here so the program continues to ask for the height until a height between 1 and 8 is entered.

    // Get Height
int n;
do
{
n = get_int("Height: ");
}
while (n > 8 || 1 > n);

With the pyramid height defined, we can begin to print the hash pattern. The key here is to split the problem up. Firstly iterate through the height of the pyramid to work on one row at a time.

    // Print hash pattern
for (int i = 0; i < n; i++)
{

Next, within the aforementioned for loop, work on printing one section at a time. First the initial spaces before the first block. Note that we iterate up to ‘n-i’, so the further we get down the pyramid the less spaces are printed.

        // Initial Spaces
for (int j = 1 ; j < n - i; j++)
{
printf(" ");
}

After that we print the left set of blocks. Here we will have one additional block for every row we go down, so we iterate up to the point where j = i.

        // Left hashes
for (int j = 0; j <= i; j++)
{
printf("#");
}

Easy one next, just print the space in the middle.

        // Gap
printf(" ");

Now the right set of blocks, using the same method as the left.

        // Right hashes
for (int j = 0; j <= i; j++)
{
printf("#");
}

And finally a new line character to start off the next row, remembering to close the for loop we are within.

        // New line
printf("\n");
}

And there we have it, a simple solution to the Mario problem using a few nested loops. A fairly easy start to the C section of the course once you figure out the logic. In a few weeks the instructor gives us a much more elegant solution to this problem using recursion, but no need to think about that yet.