0

How can I break the do while loop here in my code? The program should loop until the user inputs a valid year from the category.

When I enter the valid input, the printf still shows up even if it is meant to stop.

Here is the code below:

#include <stdio.h>
int main()
{
  float year;

  do {
    printf("Please input your year of birth :");
    scanf("%f", &year);

    if ((year >= 1946) && (year  <= 1964))
      printf("You belong to the baby boomer generation \n");
    else if ((year  >= 1965) && (year  <= 1980))
      printf("You belong to the Generation X \n");
    else if ((year  >= 1981) && (year  <= 1996))
      printf("You belong to the Millenials/Generation Y \n"); 
    else if ((year  >= 1997) && (year  <= 2012))
      printf("You belong to the Zoomers/Generation Z \n"); 
  } while(1946 > year < 2012);
}
Holger Just
  • 52,918
  • 14
  • 115
  • 123

3 Answers3

1

Your while condition does not work as you expect. For the computer, 1946 > year < 2012 is (1946 > year) < 2021; 1946 > year will be either 0 or 1, so in the end you have 0 < 2021 (or 1 < 2021), which is always true, and the loop won't stop.

Try to change it to e.g. 1946 > year && year < 2012.

See https://stackoverflow.com/a/6961728/5471218 for details.

dr_barto
  • 5,723
  • 3
  • 26
  • 47
  • When `1946 > year` is true, you have `1 < 2021` which is also true. – William Pursell Feb 15 '22 at 12:28
  • @WilliamPursell true, that's why I wrote "will be 0 most of the time" ;) But good point, I'll update my answer to show that the comparison result is irrelevant. – dr_barto Feb 15 '22 at 13:26
1
(1946 > year < 2012) 

should be

(year > 1946 && year < 2012)

and break; should be used if you want to break it somewhere like

if(year == 2000)
break;
MOTIVECODEX
  • 2,624
  • 14
  • 43
  • 78
0

Add an else condition to break the loop.

if ((year >= 1946) && (year  <= 1964))
  printf("You belong to the baby boomer generation \n");
else if ((year  >= 1965) && (year  <= 1980))
  printf("You belong to the Generation X \n");
else if ((year  >= 1981) && (year  <= 1996))
  printf("You belong to the Millenials/Generation Y \n"); 
else if ((year  >= 1997) && (year  <= 2012))
  printf("You belong to the Zoomers/Generation Z \n"); 
else
    break;