Decision making statement in c++: If, else, nested if,else if

Decision making statements are those statements which are used to write conditions or decisions to control the flow of program.

Ex: if-statement, switch, while etc.

if - statement

if-statement is simple decision making statement. It is used to control the flow and execute any particular statement depending on the logical condition.

Syntax

if(condition)
{
      statements;
}
 
Example
if(a>b)
{
      cout<<a;
}
 
In above example, if the condition (a>b) returns true then block of statements (inside the curly braces) will execute otherwise not. 
 

if - else statement

In if-statement the block of code will execute if condition is true but what if when we want to execute some code if condition is false. Here else comes. 

else-statement is always used with if-statement if we want to execute block of code when condition is false. else runs on same condition of if-statement so it doesn't require any condition.

syntax

if(condition)
{
    statement;  //execute if condition is true
}
else
{
    statement; //execute if condition is false
}

Example

if(a>b)
{
     cout<<a<<" is greater number";
}
else
{
     cout<<b<<" is greater number;

Nested if

When if statement is used inside another if or else statement, then this is called nested if statement.
 
Syntax
if(condition1)
{
    if(condition2)
    {
         statement;
    }
    else
    {
         statement;
    }
}
else
{
      statement;
}
 
Example
if(a>b)
{
     if(a>c)
    {
        cout<<a<<" is greater no";
    }
    else
    {
         cout<<c<<" is greater no";
    }
}
else
{
     if(b>c)
    {
        cout<<b<<" is greater no";
    }
    else
    {
         cout<<c<<" is greater no";
    }
}
         

else if

else if is just like another if condition in a program. It is used when we have multiple decisions. These codes are executed from top to bottom. As soon as one condition is true the statements associated with that if is executed and rest of the else-if statement is skipped.

Syntax
if(condition)
{
      statement;
}
else if(condition)
{
    statement;
}
....
....
else
{
    statement;
}
 
Example
if(age<18)
{
    cout<<"Child";
}
else if(age<40)
{
    cout<<"Young";
}
else
{
     cout<<"old";
}
 

 

 
 
 

0 Comments:

Post a Comment

If you have any queries or suggestions, please let me know!