Pages

Saturday, February 26, 2011

Selection(If Statement Compound Statement with Logical Operators)

We can further express our condition by using logical operators.

                Logical Operators:
                AND                       &&        2 condition must be true in order for output to be true
                OR                          ||             either of the two condition is true the output will be true
                NOT                       !             Inverts the output of the expression

So to enhance our program:
                Let’s say that we are going to categorize the age using the following table:

                Age                        Description
                0                              Infant
                1 – 4                       Child
                5 – 12                    Kid
                13 – 19                  Teenager
                20 up                     Adult

Program:
           
#include<iostream>
using namespace std;

main( )
{
            float age;
            cout<<”Enter your age: “;
            cin>>age;
            if(age > 0 && age < 1)
                        {
                        cout<”An Infant”;
                        }
            else if(age >= 1 && age <= 4)
                        {
                        cout<<”A Child!”;
                        }
            else if(age  > 4 && age < 13)
                        {
                        cout<<”A Kid!”;
                        }
            else if(age >=13 && age < 21)
                        {
                        cout<<”A Teenager!”;
                        }
                        else
{
                        cout<<”An Adult!”;
                        }
return 0;
}

            Here we assume that age may contain a decimal value (months / year) to accommodate infants and the others. If you can notice that each expression has AND operator (&&) except for the else. AND operator as stated, two expression must be true in order for the entire expression output to be true. For instance, let’s take the expression age >= 1 && age < = 4, the first expression which is the age >= 1 is evaluated first if true and the same with the other expression if it is true. If any of the two is false, the entire expression is set to false and the block of statement under it will be ignored and will proceed to evaluate the next if statement (else if).

            Sample output 1:
                        Enter your age: 18
                        A Teenager!

            Sample output 2:
                        Enter your age: 2
                        A child!

No comments:

Post a Comment