Boolean Logic in AND statement

Viewed 79

I created a program that calculates the divisibility by 3 and 5. If divisible by 3 print 'CS' and if divisible by 5 print 'CS1714'. If divisible by both print 'CS1714'. If not divisible by 3 or 5 print 'ERROR'.

My code executes properly. However is it possible for the Boolean && to break if say both values are false. Also why does the code print 'CSERROR' when input is 98988?

#include <stdio.h>

int main(void)
{
    int userInput;
    scanf("%d", &userInput);
    
    if((userInput % 3) == 0){
        printf("CS");
    }
    if((userInput % 5) == 0){
        printf("1714");
    }
    else if(!((userInput % 5) == 0 && (userInput % 3) == 0)){
        printf("ERROR");
    }
    
    return 0;
}
2 Answers

When the input is 98988 it is printing CSERROR because the number 98988 is divisible by 3 and that is why the first if condition is true and thus it prints CS, and then you gave another if where you are checking if the number is divisible by 5 or not, if the number is divisible by 5 then you print 1714, else you print ERROR, as 98988 is not divisible by 5 that is why it goes to the else part and prints ERROR (The last else will always true if your second if is false. So, here is a logical error). Previously it printed CS and now it printed ERROR, combinedly you are seeing CSERROR.

One is need to be clear that, the if-else blocks structures are like below, and it started implementing from a if to go further until finds a true condition or else.

if(condition){

}
else if(condition){

}
else{

}

You should check both conditions (when the number is divisible by 3 and also divisible by 5) first, then check whether it is divisible by 3 , if not then check by 5. And finally if all are false that means it is not divisible by 3 and also not divisible by 5, so print error.

The code should be like:

#include <stdio.h>

int main(void)
{
    int userInput;
    scanf("%d", &userInput);
    
    if(((userInput % 5) == 0 && (userInput % 3) == 0)){
        printf("CS1714");
    }
    else if((userInput % 3) == 0){
        printf("CS");
    }
    else if((userInput % 5) == 0){
        printf("1714");
    }
    else{
        printf("ERROR");
    }
    
    return 0;
}

Input: 98988
Output: CS

#include <stdio.h>

int main(void)
{
    int userInput;
    scanf("%d", &userInput);
    
    if((userInput % 3) == 0){
        printf("CS");
    }
    if((userInput % 5) == 0){
        printf("1714");
    }
    else if(((userInput % 5) != 0 && (userInput % 3) != 0)){
        printf("ERROR");
    }
    
    return 0;
}
Related