If… else statements in C

Control statements in C #

In all the programs we have written so far statements execute sequentially in the order in which they appear in the program. But sometimes we want statements to execute only when some condition is true For example: If the bank balance above seven figures buy a new car else renew monthly bus pass. To make such decision C provides a facility called Control Statements.

Control statements are used to alter the flow of the program. They are used to specify the order in which statements can be executed. They are commonly used to define how control is transferred from one part of the program to another.

C language has following control statements:

  • if… else
  • switch
  • Loops
    1. for
    2. while
    3. do... while

Compound statement #

A Compound statement is a block of statement grouped together using braces ({}). In a compound statement, all statements are executed sequentially. A compound statement is also known as a block. It takes the following form:

{
    statement1;
    statement2;
    statement3;
    ...
    statementn;
}

We have learned that all statements end with a semicolon(;) but the compound statement is an exception to this rule. Another important thing to understand is that a compound statement is syntactically equivalent to a single statement, this means that we can place a compound statement where a single statement is allowed. This means the following code is perfectly valid.

#include<stdio.h>

int main()
{
    int i = 100;

    printf("A single statement\n");

    {
        // a compound statement
        printf("A statement inside compound statement\n");
        printf("Another statement inside compound statement\n");
    }

    // signal to operating system everything works fine
    return 0;
}

Expected Output:

A single statement
A statement inside compound statement
Another statement inside compound statement

if statement #

If statement is used to test a condition and take one of the two possible actions. The syntax of the if statement is:

Syntax:

if (condition)
{
    // if block
    statement1;
    statement2;
}

the condition can be any constant, variable, expression, relational expression, logical expression and so on. Just remember non-zero value means true while 0 means false.

How it works:

The statements inside the if block (i.e statement1 and statement2 ) are executed only when the condition is true. If it is false then statements inside if the block is not executed. The important point to note is that braces ({}) are always required when you want to execute more than one statement when the condition is true. Also, note that statements inside the if block are slightly indented, this is done to improve readability, it is not syntactically required.

If you want to execute only one statement when the condition is true then braces ({}) can be omitted. In general, you should not omit the braces even there is a single statement to execute.

if (condition)
    statement1;

The following program prints a message if the number entered by the user is even.

#include<stdio.h>

int main()
{
    int n;

    printf("Enter a number: ");
    scanf("%d", &n);

    if(n % 2 == 0)
    {
        printf("%d is even", n);
    }

    // signal to operating system everything works fine
    return 0;
}

1st run:

Run the program and enter an even number, you will get the following output:

Expected Output:

Enter a number: 46
46 is even

2nd run:

Run the program again but this time, enter an odd number.

Expected Output:

Enter a number: 21

This time, the condition (n % 2 == 0) evaluates to false, as a result statement inside the if block is skipped.

Which statement belongs to if ? #

if (condition)
statement1;
statement2;
statement3;

Can you find which statement(s) will be omitted if the condition is false ?

If there is no brace ({}) following if statement then only the next immediate statement belongs to the if statement. The same thing is true for else and else if statements.

Therefore only the statement1 belongs to the if statement, so if the condition is false then only statement1 will be omitted. The statement2 and statement3 will be always executed regardless of the condition. Consider the following example:

#include<stdio.h>

int main()
{
    if(0)
    printf("statement 1\n");
    printf("statement 2\n");
    printf("statement 3\n");

    // signal to operating system everything works fine
    return 0;
}

Expected Output:

statement 2
statement 3

Here the condition is false , that’s why only the last two statements are executed. This verifies the fact the statement in line 6 only belongs to the if statement. As you can see it is slightly confusing to see which statement belong to the if statement, that’s why it is recommended to always use braces ( {}) to wrap statements you want to execute with the if statement.

#include<stdio.h>

int main()
{

    if(0)
    {
        printf("statement 1\n");
    }
    printf("statement 2\n");
    printf("statement 3\n");

    // signal to operating system prgram ran fine
    return 0;
}

Now you can clearly see that only first statement belongs to the if statement.

else statement #

The else statement allows us to add an alternative path to the if condition. Statements under else block are executed only when the if condition is false.

Syntax:

if (condition)
{
    // if block
    statement1;
    statement2;
}

else
{
    // else block
    statement3;
    statement4;
}

If you have only one expression to execute the else block then you can omit braces ({}). Although it is not recommended.

if (expression)
    statement1;
else
    statement2;

As already said indentation is not required, so you can also write it as:

if (expression)
statement1;
else
statement2

But why kill the readability ? Be good programmer and always indent our code.

Let's add an else statement to our previously written program.

#include<stdio.h>

int main()
{
    int n;

    printf("Enter a number: ");
    scanf("%d", &n);

    if(n % 2 == 0)
    {
        printf("%d is even", n);
    }

    else
    {
        printf("%d is odd", n);
    }

    // signal to operating system everything program ran fine
    return 0;
}

1st run:

Run the program and enter an even number.

Enter a number: 44
44 is even

2nd run:

Run the program again but this time, enter an odd number.

Enter a number: 91
91 is odd

Consider one more example:

#include<stdio.h>

int main()
{
    int a, b;

    printf("Enter two numbers: ");
    scanf("%d %d", &a, &b);

    if(a > b)
    {
        printf("%d is greater than %d", a, b);
    }

    else
    {
        printf("%d is greater than %d", b, a);
    }

    // signal to operating system everything works fine
    return 0;
}

Expected Output:

1st run:

Enter two numbers: 344 200
344 is greater than 200

2nd run:

Enter two numbers: 99 999
999 is greater than 99

Nesting if… else #

We can add if.. else statement inside if block or else block. This is called nesting of if.. else.

Syntax:

if(condition1)
{
    if(condition2)
    {
        statement1;
        statement2;
    }

    else
    {
        statement3;
        statement4;
    }
}

else
{
    if(condition3)
    {
        statement5;
        statement6;
    }

    else
    {
        statement7;
        statement8;
    }
}

We can nest if.. else statement to any depth.

How it works:

First, condition1 is checked, if it is true, then the condition2 is checked, if it is true then statements inside that if block is executed. Otherwise, the statements in else block are executed.

Otherwise, if the condition1 is false, then condition3 is checked, if it is true then the statements under that block of if statement is executed. Otherwise, the statements in the else block are executed.

The following program asks the user to enter three numbers and displays the larger of them.

#include<stdio.h>

int main()
{
    int a, b, c, larger;

    printf("Enter three numbers: ");
    scanf("%d %d %d", &a, &b, &c);

    if(a > b)
    {
        if(a > c)
        {
            larger = a;
        }

        else
        {
            larger = c;
        }
    }
    else
    {
        if(b > c)
        {
            larger = b;
        }

        else
        {
            larger = c;
        }
    }

    printf("Largest number is %d", larger);

    // signal to operating system everything works fine
    return 0;
}

Expected Output:

1st run:

Enter three numbers: 12 35 54
Largest number is 54

2nd run:

Enter three numbers: 77 23 871
Largest number is 871

Matching if.. else parts #

Sometimes it becomes confusing to associate an else statement with the if statement. Consider the following example:

if(a<10)
    if (a % 2 ==0)
        printf("a is even and less than 10\n");
else
printf("a is greater than 10");

Which if statement is associated with the else block ? According to the way code is indented you might think else belongs to the first if statement, but it is not. The compiler does not associate if and else statement according to indentation, it matches the else part with the closest unmatched if part. So the else statement is associated with the second if statement.

We can always avoid such complications using braces ({}).

if(a < 10)
{
    if (a % 2 ==0)
    {
        printf("a is even and less than 10\n");
    }

    else
    {
        printf("a is greater than 10");
    }
}

Now everything is crystal clear.

else if statement #

if... else is a bi-directional statement, means they are used to test a condition and take one of the possible two action. What if we have more than one conditions ? Sure we can handle more than one conditions using nested if... else (as we did in the program p1212), but there is a better way using if-else-if statements. Its syntax looks like this:

if(condition1)
{
    statement1;
}

else if(condition2)
{
    statement2;
}

else if(condition3)
{
    statement3;
}

...
else
{
    statement4;
}

Here each condition is checked, when a condition is found to be true then statements in only that block are executed all other conditions will be skipped and program control comes out of if... else statement. If none of the conditions is true then statements in the else block are executed.

Using else if statement we can write nested if-else statement in more compact form.

Let's rewrite program p212 using else if statement.

#include<stdio.h>

int main()
{
    int a, b, c, larger;

    printf("Enter three numbers: ");
    scanf("%d %d %d", &a, &b, &c);

    if(a > b && a > c)
    {
        larger = a;
    }

    else if(b > a && b > c)
    {
       larger = b;
    }

    else
    {
        larger = c;
    }

    printf("Largest number is %d", larger);

    // signal to operating system everything works fine
    return 0;
}

As you can see the program written using else-if statement is more compact and easy to understand than it's nested equivalent.