1

I am currently in the process of finishing Problem Set 1 from CS50 2019, which involves creating a pyramid out of hashes. The pyramid must be made by the user inputting a number between 1 and 8 (inclusive). I've gotten to the point where I ask the user for an integer between 1 and 8 and keep on asking until it is received. I have watched the walkthrough and seen the hints, but I am still confused as to how in the world to do this. Can someone please provide me with some insight on this? Here is my current code:

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

int get_positive_int(string prompt);

int main(void)
{
    int i = get_positive_int("Height: ");
    printf("Stored: %i\n", i);
}

// Ask for integer between 1 and 8
int get_positive_int(string prompt)
{
    int n;
    do
    {
        n = get_int("%s", prompt);
    }
    while (n > 8 || n <= 0);
    return n;    
}

Thanks!

0

I'm a little confused on what you don't understand. The code above asks for the height and correctly gets a number from 1 to 8 inclusive. (You could also have used n < 1 instead of n <= 0, but both are equally correct here. ) IF you don't understand what you did, please edit the question and add more detail and context of what you don't understand. But, as a guess, here's an explanation of how a do/while loop works.

A do/while loop will always execute at least once because the test follows the loop, it doesn't come at the beginning. So, when the code hits the test, it checks whether the input is OUTSIDE the desired range. IF it's outside the desired range, the loop repeats until we get what we want.

Now, if you're trying to figure out how to attack building the pyramid, do it in steps.

  • First, print out a line with a single #.
  • Next, print out a pyramid with a single hash on each line and the right number of lines.
  • Next, a pyramid with the correct number of # on each line.
  • Finally, work on the spaces. (THis will probably be the most difficult part.)

Happy coding!

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

2
  • I was confused as to how to start trying to build the pyramid, I understood my code for prompting the user to enter an integer with the requirements. And as for your clarification on the pyramid part, that cleared it up for me. Thank you!
    – AK-25
    Apr 8 '19 at 9:23
  • Glad I could help. If you're satisfied, could you please accept the answer? Otherwise, the question will sit in the unanswered question pool forever.
    – Cliff B
    Apr 8 '19 at 16:20

You must log in to answer this question.

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