0

This is my code for the mario problem:

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

int main(void)
{

int pyramid_height = 0;

do
    {
    printf("Please enter the half pyramid's height\n");
    pyramid_height = GetInt();
    } while (pyramid_height < 0 || pyramid_height > 23);

//declaring 3 int variables in the first part of the for loop:
//'i' is the for loop counter, and should effectively be the line/row number
//'hash' should be the line number + 2, e.g. the first row (row 0) has 2 hashes printed.
//'spaces' should be the pyramid_height - hash, e.g. the first row (row 0) has 6 spaces on it if pyramid_height == 8, as 8-2 = 6     

for (int i = 0, hash = i + 2, spaces = pyramid_height - hash; i < pyramid_height; i++)
    {    

    for (int j = 1; j <= spaces; j++)
        {
         printf (" ");
        }

    for (int k = 1; k <= hash; k++)
        {
        printf ("#");
        }

    printf("\n");
    }

}

Must be getting close now... But when I run this code, this is the kind of stuff that gets printed:

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

The number of lines is equal to pyramid_height, but each line prints 6 spaces and 2 hashes (Aside: I had to change j and k to initialise at 1 instead of 0 too, as when it was set to 0 it was giving 7 spaces and 3 hashes, this 0-index stuff is hurting my brain a bit...)

so, It looks like the variables 'hash' and 'spaces' are not updating as 'i' changes each time the main for loop runs again to create a new line - what have I done wrong here?

0

the first part of the for loop initializes variables. It looks at this initialization only the first time it runs. So when you say hash = i + 2 the first time it runs the for loop, it looks at what the value of i is at that time, 1 time only, and sets hash = i + 2. It then no longer looks at that part of the for loop anymore, and instead only looks at the 2nd and 3rd arguments for all subsquent loops.

If you want hash to keep updating, you can initialize it like that, but you need to update it within your loop like so:

for (int i = 0, hash = i + 2, spaces = pyramid_height - hash; i < pyramid_height; i++)

{

//hash = whatever formula you want to use to update it, probably the same one as in your for loop argument

Keep in mind, you will have to do this with your spaces variable as well.

You must log in to answer this question.

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