if-else Statements

if-else Statements

    Till now,we just threw light on uses of 'if'. Now its about time we should head for the counter part of 'if' i.e. 'else'. Its very easy to take down this topic in one shot.  So we'll discuss just a single program regarding this topic.
    What basically 'else' refers to is the left over of 'if'. In simple language, consider we write our 'if' condition as if(i<8), then this 'if' will include all the values of i which are smaller than 8(not including 8). Now the left over of this 'if' are the values of i including 8,9,10 ......and all above values.These values are covered in else.The syntax of writing 'if' with 'else' is as follows:

if(condition)
    statement 1;
else
    statement 2;

Remember, unlike 'if' statements we do not need to write any condition in 'else' statements which are covered by a pair of brackets. All the conditions which are not a part of 'if' are automatically covered in 'else'. In the last example we read in 'if' topic which had a logical NOT operator (!), the second 'if' can be replaced by else.Why is it so you ask? It is because all the conditions not satisfied by 'if' were FALSE. And NOT operator changes all these FALSE conditions to TRUE. So indirectly it is including all the conditions left by 'if'. Lets consider an example.

#include<iostream>
#include<cstdlib>

using namespace std;

int main()
{
    int a;
    cout<<"\nEnter value of a : ";
    cin>>a;
    if(a==2609)
        cout<<"\n Holla!!!! Thats my birthday";
    else
        cout<<"\nNop! Thats not my BD.";
    system("PAUSE");
    return 0;
}

For creating a link between this program with the one we studied earlier(one having NOT operator), I'll only say,we could have written that program in the following way:

#include <cstdlib>                     
#include <iostream>                     //Header Files
using namespace std;
int main()                             //main function
{
    system("CLS");                     //clears any printed, if any
    int condition;
    cout<<"\nEnter value of condition : ";
    cin>>condition;
    if(condition)        // 1st if
        cout<<"\nYour condition evaluates to TRUE.";
    else                    // Replacement of 2nd if
        cout<<"\nYour condition evaluates to FALSE.";
    system("PAUSE");                  // Freeze the screen to show the output
    return 0;
}

The concept is easy and self explanatory.The next topic we'll be covering is "multiple statement under if and else".

Written By T-Rex
<<'if' Statements                                  Home                              Multiple statement under if-else>>

No comments:

Post a Comment