Home > OS >  Why is this do while loop not working in c?
Why is this do while loop not working in c?

Time:02-21

Sorry for what may be a commonly asked question but my code is a lot simpler to any other questions I've seen and it still isn't working.

My code:

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

int main(void)
{
  int n;
  do
  {
    n = get_int("Width: ");
  } 
  while (n < 1);
}

This code is an exact copy from Harvard's cs50 course. What I expect is if n is less than 1, it will prompt the user again until a value of 1 or above is entered. However, it is only asking me for width once even when I enter 0 and finishing.

CodePudding user response:

This is the way to handle this kind of issues:

Either you start using a debugger and put a breakpoint at the following line:

int main(void)
{
  int n;
  do
  {
    n = get_int("Width: ");
  } // here you set your breakpoint
  while (n < 1);
}

You add a watch for the variable n and check the value.

Another approach is the following:

int main(void)
{
  int n;
  do
  {
    n = get_int("Width: ");
    printf("The value of n is [%d]", n); // this line shows the value of n
  } 
  while (n < 1);
}

Bottom line: you need to investigate the value of n, either using a debugger, either showing it on screen.

CodePudding user response:

You are including the cs50 library at the top but have you imported it on your PC if not make sure to include #include <cs50.h> atop your file and compile with the -lcs50 flag. CS50 Library for C

  • Related