'Problems in if else statements in C
#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 1:[1]
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");
}
Solution 2:[2]
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;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Killar. exe |
| Solution 2 | Python learner |
