cif-statementrelational-operators

Else condition not working even tho there is no error


I am making a program in c using if else conditions and it is running perfectly fine without any errors but it is not running the else condition(i.e. even if I am giving it the input where the else condition should be printed, it is giving me the else if condition and not the else condition), here is the code

if(Number_Of_People==1){
        printf("Show us your identification so we can proceed!");
    }
    else if(1<Number_Of_People<=6){
        printf("Show us the identification of each member so that we can proceed!");
    }
    else 
    {
        printf("Sorry, we dont have rooms for so many people!");
    }

Solution

  • The expression in the if statement

     else if(1<Number_Of_People<=6){
    

    may be equivalently rewritten like

     else if( ( 1 < Number_Of_People ) <=6 ){
    

    The relational operator < yields either 0 or 1 depending on whether the expression with the relational operator is logically false or true.

    Thus the result of the subexpression ( 1 < Number_Of_People ) either equal to 0 or 1 in any case is less than 6.

    So this if statement will be always evaluated if the preceding if statement will be skipped.

    You need to rewrite the above if operator like

    else if( ( 1 < Number_Of_People ) && ( Number_Of_People <= 6 ) ){