Home > Software design >  Problems in if else statements in C
Problems in if else statements in C

Time:03-23

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

int main(){

int month, day;
printf("Enter the input : ");
scanf("%d %d",&month,&day);

if (day == 1 &&  month==1 || month == 2 || month == 3 || month ==4){
    printf("Green\n");
}
else if(day == 2 && month == 5 || month == 6 || month ==7 || month ==8 ){
    printf("Red");
}

return 0;
}

In the above code whenever I choose d = 1 and month = 1-4 , it is supposed to print green which it does correctly. The problem is when I choose day = 2 & month = 8 or 7 or 6 it is supposed to print red but it is printing green. Am I missing something here?

CodePudding user response:

you need to check the day and month diffently. Try this instead:

if (day == 1 &&  (month==1 || month == 2 || month == 3 || month ==4)){
    printf("Green\n");
}
else if(day == 2 && (month == 5 || month == 6 || month ==7 || month ==8)){
    printf("Red");
}

CodePudding user response:

It just works fine as you expected.
Maybe, you forgot that your first input is month and day is second. Try again now.

#include <stdio.h> 
#include<stdlib.h> 
int main(){ 
int month, day; 
printf("Enter the input : "); 
scanf("%d %d",&month,&day); 
if ((day == 1 && month==1) || month == 2 || month == 3 || month ==4)
{ printf("Green\n"); } 
else if(day == 2 && month == 5 || month == 6 || month ==7 || month ==8 ){ 
printf("Red"); } 
return 0; 
}
  • Related