I managed to complete the hacker version of the mario.c problem in pset1 using "for" loops. However, when I re-tried the problem using "if" and "else if", I could not achieve similar results. Here is my code:
#include <stdio.h>
#include <cs50.h>
int main(void)
{
printf("Please enter a number\n");
int h = GetInt();
int i = 0;
if (h > 0)
{
for (int x = 1; x <= h; x++)
{
if (i <= h-x)
{
printf (" ");
i++;
}
else if (h-x < i && i <=h)
{
printf ("#");
i++;
}
else if (i == h+1)
{
printf (" ");
i++;
}
else if (h+1< i && i <= h+x)
{
printf ("#");
i++;
}
printf ("\n");
}
}
}
My logic is as follows: h
is the height input from the user, x
is the row as measured from the top of the pyramid and i
is the block (either whitespace or hex) from the left. The first "if" condition is that a whitespace is added and i
is incremented by one when it is less than h-x
, until it is equal to h-x+1
when a hex is added. The same logic is followed until both sides of the row are finished, when x
then is incremented by one.
However, when I input a value of, say, "5", I obtain 3 whitespaces and 2 hexes only, each one occupying a new line! Could someone explain why this code does not work? Thank you!