0

I'm working on the mario staircase right now and everything works so far except printing out the hash symbols correctly. That's the code I've written so far:

 int main(void)
{
// declare variable
int height;

// prompt user for number from 0 to 23
do
{
    printf("Height: ");
    height = get_int();
}
while ( height > 23 || height < 0);


// loop for making the pyramide
 for (int row = 1; row <= height; row++)
 {
    for (int space = (height - row); space > 0; space--)
    {
        printf(" ");
    }
    for (int hash = 1; hash <= height + 1; hash++)
    {
        printf("#");
    }
  printf("\n");
 }
}

Now if I execute mario.c and type for example "Height: 5", that's the output I get:

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

I don't understand why the first line prints 5 hashes instead of one. If I code it so that (int hash = 1), shouldn't the first line print only one #, and afterwards add another one because of the hash++?

I would really appreciate it if someone could explain what I did wrong here!

1 Answer 1

2

Your hash loop prints height+1 hashes every time (one per iteration of the inner loop, iterated height+1 times). This does not change over the several rows, as all the variables used have the same values in every iteration of the outer loop.

Try using row, not height, in that loop, so instead of

for (int hash = 1; hash <= height + 1; hash++)

use

for (int hash = 1; hash <= row + 1; hash++)

BTW, you really should become comfortable with zero-based indexing. There's no way to avoid it once you meet arrays.

1
  • Thanks so much! So obvious in hindsight, haha. And I'll take that advice to heart!
    – hryyy
    Aug 17, 2017 at 15:28

You must log in to answer this question.

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