Return to Topic Menu | Computer Science Main Page | MathBits.com | Terms of Use

Demo successive "if" Statements

/*This program expresses my preferences of temperatures.  Depending upon the conditions which need to be checked, a successive series of "if" statements may work nicely.  
BUT successive "if" statements can create a trap for you if you are not careful.  See if you can see what is wrong with the logic used in the program below.*/
 
#inlcude <iostream.h>
#include <stdlib.h>

int main(void)
{
     system("CLS"); 
     int temp;     

     cout<< "Please enter the temperature:  ";
     cin>> temp;

    if (temp < 32)
    {                      
 
           cout<<"Brrrr!!! Where's the lodge?";
     }

    if (temp >85)
    {                      
 
           cout<<"Sweat city!!! Where's the pool?";
     }

     cout<< "Now, this temperature I like!!";

     return 0;
}
/*The problem is that the last line ("Now, this temperature I like!!") is printed EVERY time - even when one of the "if" statements is true.  This most likely was not the intent of this program.  The
"if ... else if ... if" structure would solve this problem more efficiently than adding yet another "if" statement to this program.*/

 

 Return to Topic Menu | Computer Science Main Page | MathBits.com | Terms of Use