[SOLVED] Problems in if else statements in C

Issue

#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?

Solution

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");
}

Answered By – Killar. exe

Answer Checked By – Gilberto Lyons (BugsFixing Admin)

Leave a Reply

Your email address will not be published.