How to Use If Statements in C++

A programmer may require putting some conditions in the code i.e. the code should execute some set of statements if an event occurs or a condition is satisfied, else it has to execute different set of statements. If we do not use these conditions every time the program runs, it will show the same behavior and will not adapt to the changes of certain conditions such as change in value of a variable etc. For this purpose all of the programming languages provide some commands. If and else statements are one of such commands to check certain conditions. They are very simple to use and you can master them by simply going through this article. I will describe these conditions below.

Instructions

  • 1


    First of all you need to know about the comparison operators that are used with if or else statements. They are described below.


    a: “>  is used for greater than” e.g. 7>3
    b: “<  is used for less than”   e.g. 4<7 c: “>=  is used for greater than or equal to” e.g. 7>=7
    d: “<=  is used for less than or equal to”  e.g.  7<=7
    e: “== is used for equal to” e.g.  5==5
    f: “!=  is used for not equal to” e.g. 5!=7



  • 2

    The syntax of if, if else and if is shown below using an example.


    # include


    using namespace std;


    int main (){


    int no1,no2;


    cout<<”enter number  1: ”; cin>>no1;


    cout< cin>>no2;


    cout< if(no1>no2){


    cout<<”number 1 is greter”;


    }


    else if(no1< no2)


    {


    cout<<”number 2 is greter”;


    }


    else{


    cout<<”Both numbers are equal”<;


    }


    return 0;


    }

  • 3

    The example shown above uses all if, else if and else statements. The comparison is done inside the brackets of if or else if statement and then depending on if the statement is true the code inside square brackets will execute.


    Else if statement is only checked if the if statement is false, else also works like this i.e. if all of the statements above else are false, else statement will execute in that case.


    For example in our sample code, if you enter, no1=5 and no2= 6 then first condition is checked that if(5>6), as you can see that it is false, the code will jump to else id statement and here we have else if(5<6), and as you can see this is true, the compiler will show on the terminal that “number 2 is greater”. In case you enter n01=no2=6, in this case if and else if statements will be false and else statement will be executed displaying “Both numbers are equal”.

Leave a Reply

Your email address will not be published. Required fields are marked *


× 6 = thirty six