0

I have been researching and watching the videos many times and I have spent 3 hours on this code and I have not figured much out. Right now I have the code printing # as only one character in an infinite loop. I'm ready to just give up!

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

int main(void)
{
    int height, row, hash;

    do
    {
        printf ("Height ");
        height = GetInt();
    }
    while ((height < 0) || (height > 23));

    for (row = 0; row <= height; row++)
        for (hash = 1; hash <= row; hash--)
            printf ("#\n");
}

I know this is very basic code but I am brand new to the C programming language.

2 Answers 2

1

Your problem is in the second for loop. You start hash at the value of 1, and as long hash <= row holds true, you keep looping.

Let's see how the loops execute:

  • row is 0. row <= height is true so we execute.
    • hash is 1. hash <= row is false so we don't execute.
  • row++
  • row is 1. row <= height is true so we execute.
    • hash is 1. hash <= row is true so we execute.
      • we print #\n
    • hash--
    • hash is 0. hash <= row is true so we execute.
      • we print #\n
    • hash--
    • hash is -1. hash <= row is true so we execute.
      • we print #\n
    • hash--
    • hash is -2. hash <= row is true so we execute.
      • we print #\n
    • hash--
    • hash is -3. hash <= row is true so we execute.
      • we print #\n
    • and so on......

That's where the infinite loop occurs. I'll leave the solution to you.

As a hint: are you sure that the initialization and condition in the second loop are correct?

0

I have nested for loops. The main one for height, that prints nothing right away, then a food loop for spaces that prints " " then I have one for hashes that prints "#" The at the end of those two loops but inside the first for loop I increment and decrement spaces and hashes and then print a new line.

You must log in to answer this question.

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