0

I'm really close to solving this problem but can't seem to figure out why I'm not getting the correct result (i.e. a pyramid made of #'s that looks like this: http://cdn.cs50.net/2016/x/psets/1/pset1/pset1.html#itsa_mario)

In my code, you'll notice I've substituted s for " " for the time being (just to make it easier for me to see/count). I seem to be getting the spaces correct but the hashes (or b for bricks) get stuck printing only 2s at a time before jumping to the next line. I intended for the number of "b" to increase every time the loop is run but this is not happening despite writing b++. Can someone please help me identify the issue as I've been trying to solve this for going on 3 days now :(

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

int main (void)
{
    /*local variable declaration for height*/
    int h = 0;

    /*do while loop to get an int from user*/
    do {printf ("Enter a positive integer for the height of a Pyramid, no larger than 23: ");
        h = GetInt();
    }
    while (h >= 24 || h <= 0);

    /*initialize count for "#" and ' ' variables*/
    int i = 2;
    int h2 = h;

    /*instructions for building pyramid -- first establishing the loop as a function of height...*/
    for ( ; h > 0; h--)
    {
        //then print the spaces
        int s = h + 1 - i;
        for ( ; s > 0; s--)
        {
            printf ("s");
        }
        //...then print the bricks
        for (int b = 2; b>0 && b<h2; b++)
        {
            printf ("#");
        }
        //new line then repeat
        printf ("\n");
    }
}
2
  • b must be incrementing, otherwise you would be stuck in an infinite loop. But why are you taking b from 2 to h2? This causes (h2-2) "#", in every row, instead of increasing as we move down.
    – abhishek
    Jun 22, 2016 at 13:50
  • I see what I did! Thank you for the clarity. I guess it doesn't matter how many times you look at something, you may need an extra pair of eyes to "see" what you need to. (Kind of like how they always recommend printing out your papers to edit them by hand instead of doing so on a screen). It look like I kept running the same thing twice in my 2nd nested for loop, resulting in "#" being printed twice every time. Since there was no reference to "h2" (the copy of the height input), the formula for "b" (#/bricks) would not change and would instead keep doing the same number of iterations (2).
    – Jon S
    Jun 22, 2016 at 17:08

1 Answer 1

1

you logic in nested for Loop is incorrect. I would stard b from h2-h unitil 0 and decrement b instead of incrementing.

 for (int b = (h2-h); b >= 0; b--)
 {
       printf ("#");
 } 

You must log in to answer this question.

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