1

I have created a program that asks for two numbers between 100 & 150. Also the difference between these numbers must be less than or equal to 10. I run the program but it doesn't end it continually loops even when I enter the correct values.

#include <stdio.h>
#include <stdlib.h>

#define FALSE 0
#define TRUE !FALSE

int main(void)
{
  double a, b;
  double epsilon = 10.000000001;
  int flag_1, flag_2;

  flag_1 = FALSE;
  flag_2 = FALSE;
  do
  {
      printf("Enter in two values between 100.0 & 150.0\n");
      printf("The difference between each value must be less than or equal to 10.0\n\n");
      printf("Enter in value a: ");
      scanf("%lf", &a);
      printf("Enter in value b: ");
      scanf("%lf", &b);

      if (((a < 100.0)||(a > 150.0))||((b < 100.0)||(b > 150.0)))
      {
        printf("Error Enter between 100.0 & 150.0\n\n");
        flag_1 = TRUE;
      }
      else if (((a - b) > (epsilon))||(((a - b)*(-1)) > (epsilon))) 
      {
        printf("Error\n\n");
        flag_2 = TRUE;
      }
      else
      {
        printf("Values a & b are: a = %lf, b = %lf\n\n", a, b);
      }
  }while((flag_1 == TRUE)||(flag_2 == TRUE));

  system ("pause");
  return 0;
}
3
  • Try initialising a and b also Commented May 26, 2015 at 6:13
  • Try using %f in all the printfs. Also, try adding flag_1 = FALSE; flag_2 = FALSE; at the start of the do...while loop. Commented May 26, 2015 at 6:14
  • 2
    Reset the flags inside the loop, otherwise your condition will be false once it was false. In other words. Move flag_1/2 == FALSE; at inside the do loop before you check the validity of the items. Commented May 26, 2015 at 6:17

2 Answers 2

2

You need to reset the values of flag_1 and flag_2 to FALSE right after

do {

Otherwise, their values from the previous iteration of the loop persist. Use:

do {
   flag_1 = flag_2 = FALSE;
Sign up to request clarification or add additional context in comments.

2 Comments

I don't understand why when I enter correct values and no flag is set to TRUE it repeats. Although the program works now so thank you.
Because once either of those values is set to to TRUE they never get set back to FALSE in your code, so if either gets set just once, the loop will run forever.
1

You have to reset the flags to FALSE in the beginning of the while loop. Assume this case: a =180 and b =50. The program will enter in the if case and flag_1 is set to TRUE. Since it is TRUE, the loop will run again. Now, in this iteration, even if you enter right values of a and b, since the flag is TRUE, the program will keep running.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.