Search code examples
cif-statementintprintflogical-or

If statement gives wrong result


I am trying to write a program which takes user input for an area code and based on that it displays the corresponding Area which the area code is for based on this table:

Area code ----------- Major City

229 --------------------- Albany

404 --------------------- Atlanta

470 --------------------- Atlanta

478 --------------------- Macon

678 --------------------- Atlanta

706 --------------------- Columbus

762 --------------------- Columbus

770 --------------------- Atlanta

912 --------------------- Savannah

This is my code below the problem i have is that the IF statement gives me incorrect results such as for example if i input 912 it will give me "Atlanta" which is incorrect since in the IF statement it says if 912 is equal to user input "Savannah" should display.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdbool.h>
int main(){

int AreaNum;

printf("enter a area code: ");
scanf("%d", &AreaNum);

if (AreaNum == 229){
printf("Albany");
}else if (AreaNum == 404 || 470 || 678 || 770){
printf("Atlanta");
}else if (AreaNum == 478){
printf("Macon");
}else if (AreaNum == 706 || 762){
printf("Columbus");
}else if (AreaNum == 912){
printf("Savannah");
}else
printf("Area code not recognized");

  return 0;
}


Solution

  • Such an if statement like this

    }else if (AreaNum == 404 || 470 || 678 || 770){
    

    is equivalent to the following

    }else if ( ( AreaNum == 404 ) || ( 470 )|| ( 678 ) || ( 770 ) ){
    

    So if for example the first sub-expression AreaNum == 404 evaluates to false then the second and subsequent expressions like ( 470 ) are not equal to zero so they evaluate to true and the whole expression yields the value true.

    From the C Standard (6.5.14 Logical OR operator)

    3 The || operator shall yield 1 if either of its operands compare unequal to 0; otherwise, it yields 0. The result has type int.

    And neither 470, nor 678 or 770 in the above expression are equal to 0. So the condition in this if statement will always yield true independent on whether AreaNum is equal to 404 or not.

    That is the above if statement may be equivalently rewritten the following way

    }else if ( ( AreaNum == 404 ) || ( 470 != 0 )|| ( 678 != 0 ) || ( 770 != 0 ) ){
    

    It seems you mean the following

    }else if ( ( AreaNum == 404 ) || ( AreaNum == 470 )|| ( AreaNum == 678 ) || ( AreaNum == 770 ) ){