0

My code is down below. Everything above the for loop is fine. I need help with printing spaces and hashes.

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

int main(void)
{
int h;

do
{
    printf("How tall should the pyramid be? (between 1 and 23)\n");
    h = GetInt();
} 
while (h<1 || h>23);

printf("Your number checks out\n");
for(int spaces = h; spaces == 0; spaces--)
{
    printf("#"); 
}
}
0

First, you want to make your program print each line before worrying about what's in those lines. That's your for-loop.

I like to start from the expected output and work my way backward. It may or may not work for you. Try drawing a half pyramid for a few lines. I tried 3 and 4. Then I figure out how many spaces and hashes should be in each line. Relate them to the height of the half pyramid and which line they are in. Try to see the pattern and you can come up with a formula for space and hash.

How do you print spaces a number of times and then print hashes a number of times in each line? Remember, you only want to make a new line when you're done with hash part of each loop.

I struggled to print space for awhile, so this might help if you're in the same situation. printf(" ");

Good luck!

0

Right now, you only have one for loop, but you'll need to consider printing multiple loops, some inside others. Your "master loop" is going to involve printing int h number of lines. In addition, though, each line is going to involve printing a specified number (based on the variable h) of the characters " " and "#", hence the nesting of loops.

In other words, think of this pseudocode:

Print line
    Print spaces
    Print hashes
2
  • What exactly do you mean by printing lines? I don't quite understand this... – user10938 Feb 24 '16 at 23:13
  • Each line/row of your pyramid is composed of two elements: spaces and hashes. When I say "print line," I mean "print a combination of these two characters." Each character require its own for loop. Even though you don't see the spaces when you look at the pyramid in the pset specs, you still need to print them. – Peter Feb 24 '16 at 23:28
0

In the above code, printf() isn't being called because of the conditions inside your for loop. Recall that this:

for(int spaces = h; spaces == 0; spaces--)
{
    printf("#"); 
}

is the same thing as writing this:

int spaces = h;
while (spaces == 0)
{
    printf("#");
    spaces--;
}

In both cases, printf() will not be called because spaces is equal to h, not zero.

Also, don't forget to return 0 at the end of your program.

You must log in to answer this question.