0

After a certain number of iterations through the loops (lines 16 to 21), I expect the program to stop printing out dots since the "dotcount" should be equals to 0. However, an unnecessary dot is still printed out in the last line of the output and I do not understand why this is logically so. Any help would be greatly appreciated!

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

int main(void)
{
    //prompt the user for how high they want the pyramid to be
    int height;
    do
    {
        height = get_int("What's the height of the pyramid? \n");
    } while (height < 1 || height > 8);

for (int i = 0; i < height; i++)
{
  int hexcount = i + 1;
  int dotcount = height - hexcount;
  do 
  {
      dotcount--;
      printf(".");
  } while (dotcount >= 1);

  do
  {
      printf("#");
      hexcount--;
  } while (hexcount != 0);

  printf("\n");
}
    printf("\n");
}
0

Turns out what I've been doing wrong all along is that I should be just using a simple "While" loop instead of a "Do...While..." loop for my dotcount block of code! I've fixed the problem with the following block of code to replace the "Do...While..." block.

while (dotcount > 0)
  {
      printf(" ");
      dotcount--;
  }

Revisiting the following video by CS50 definitely helped me to see and understand where my conceptual problems lay and I would recommend anyone encountering the same problem as I to go check it out too!

2
  • Yep, tried it myself. The type of loop was not the correct one. Don´t forget to check the thread as answered – ALL May 24 '20 at 18:30
  • Yes, you found the cause. I added a printf to help debug, here is the link. You might find it useful late when you need to debug segmentation faults. – stensal May 24 '20 at 22:14
0

Ok.. another approach. Maybe it is of the do while, which is a foot-controlled loop. That means, the loop runs first and then it checks the condition. In your case the printf first prints the "." and after that the code recognizes "Oh, ok.. <1). A head-controlled loop might help (e.g. for-loops).

You must log in to answer this question.

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