Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

C Nested if statement

In C programming, it is possible to place if control statement inside another if-block or else-block.

Basic structure

if(condition1) // outer if-block
{
    if(condition2)
    {
        block1
    }
}
else // outer else-block
{
    if(condition3)
    {
        block2
    }
}

In the above structure, if condition1 becomes true, program control enters into outer if-block. Then it checks for condition2. If condition2 is true, block1 is executed.
After execution of block1, control is transferred directly to the statement after the outer else-block.
If condition1 becomes false, program control enters into outer else-block skipping outer if-block. Then it checks for condition3. If condition3 is true, block2 is executed. After execution of block2 and outer else-block control is transferred directly to statement after it.

C Nested if-else statement

In C programming, it is possible to place if-else control statement inside another if-block or else-block.

It works similar to the nested if statement.

Basic structure

if(condition1)
{
        if(condition2)
        {
                block1
        }
        else
        {
                block2
        }
}
else
{

}

Example

#include<stdio.h>
int main()
{
    int david,john,andrew;
    david = 19;
    john = 24;
    andrew = 21;
    if(david>john)
    {
        if(david>andrew)
        {
            printf("\n david is older than john & andrew");
        }
        else
        {
            printf("\n Andrew is older than david & john");
        }
    }
    else
    {
        if(john>andrew)
        {
            printf("\n john is older than david & andrew");
        }
        else
        {
            printf("\n Andrew is older than david & john ");
        }
    }
    return 0;
}

Output

john is older than david & andrew

 

Leave a reply