0
#include <stdio.h>

int main(){
  int age;
  printf("Enter your age : ");
  scanf("%d",&age);

  while(age !=0){
    if(age > 21 )
      printf("you can drink buddy\n");
      break;
    else if(age<21)
      printf("you can't drink it buddy \n");
      break;
  }
  
  
  return 0;
  
}

so I wrote this program to check if they are allowed to drink or not according to their age but i don't know why its shows error when i added the break statement which was creating infinite loop

Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39
Sad
  • 13
  • 2
  • 2
    `"but i don't know why its shows error"` -- What "error" does it show? Please elaborate. – Andreas Wenzel Jan 25 '22 at 15:31
  • 2
    Side note: In your program, you specify what should happen when `age > 21` and what should happen when `age < 21`, but you don't specify what should happen when `age == 21`. Is that intended? – Andreas Wenzel Jan 25 '22 at 15:34
  • **Never say “I got an error” without telling us what the error is.** Cut & paste the exact error so that we can see what it says. If we can't see the error, we can't tell what the problem is. It's like taking your car to the mechanic and saying "The car makes a noise" but not telling what the noise is. – Andy Lester Jan 25 '22 at 15:40
  • just some design critique, using a `while` loop here makes no sense. `age` doesn't change in the loop, so breaking after one iteration under certain conditions are met (or infinitely looping if `age==21` as pointed out by AndreasWenzel) is odd behavior for either case. Either add the ability for the user to re-enter the age each iteration (move `scanf` inside the loop), or drop the loop all together and do `if (age >= 21) { ... } else { ... }` – yano Jan 25 '22 at 15:46

1 Answers1

3

You just need to add {'s since there are now more than one line in the if statements.

By default an if statement without {'s includes the next line in the if. Without the {'s the break statement is not in the if so you get an error because the else if does not come directly after and if. While indentation is useful for readability in java it doesn't influence how the code runs.

if(age > 21 ){
  printf("you can drink buddy\n");
  break;
}
else if(age < 21){
  printf("you can't drink it buddy \n");
  break;
}
H.S.
  • 11,654
  • 2
  • 15
  • 32