OverIQ.com

if-else statements in C

Last updated on July 27, 2020


Control statements in C #

In all the programs we have written so far statements execute sequentially in the order in which they appear. But sometimes we want statements to execute only when some condition is true For example, If the bank balance is above seven figures buy a new car else renew monthly bus pass. To make such decisions 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
    • for
    • while
    • 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:

1
2
3
4
5
6
7
{
    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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#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:

1
2
3
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: #

1
2
3
4
5
6
if (condition)
{
    // if block
    statement1;
    statement2;
}

the condition can be any constant, variable, expression, relational expression, logical expression and so on. Just remember that in C, any non-zero value is considered as true while 0 is considered as 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 are skipped. The braces ({}) are always required when you want to execute more than one statement when the condition is true. Also, note that the statements inside the if block are slightly indented. This is done to improve readability, indentation 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 if there is a single statement to execute.

1
2
if (condition)
    statement1;

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#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 and you will get the following output:

Expected Output:

1
2
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? #

1
2
3
4
if (condition)
statement1;
statement2;
statement3;

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

If there are no braces ({}) following the if statement then only the next immediate statement belongs to the if statement. The same thing is true for else and else-if clause (else and else-if clause are discussed later in this chapter).

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. The following example demonstrates this fact:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
#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:

1
2
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. At a glance, it is slightly confusing to determine which statement belongs 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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#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.

The else clause #

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

Syntax:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
if (condition)
{
    // if block
    statement1;
    statement2;
}

else
{
    // else block
    statement3;
    statement4;
}

As usual, if you have only one statement in the else block then the braces ({}) can be omitted. Although, it is not recommended.

1
2
3
4
if (expression)
    statement1;
else
    statement2;

As already said, indentation is not required, so the above code can also be written as:

1
2
3
4
if (expression)
statement1;
else
statement2;

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

Now, let's add an else clause to our previously written program.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
#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.

1
2
Enter a number: 44
44 is even

2nd run:

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

1
2
Enter a number: 91
91 is odd

Consider one more example. The following program determines the larger of the two entered numbers:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
#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:

1
2
Enter two numbers: 344 200
344 is greater than 200

2nd run:

1
2
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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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, the condition1 is checked, if it is true, then the condition2 is checked, if it is true then statements inside the if block (lines 4-7) are executed.

Otherwise, the statements in the else block (lines 10-13) are executed. Otherwise, if the condition1 is false, then the condition3 is checked, if it is true then the statements under the if block in lines 19-22 are executed. Otherwise, the statements in the else block (lines 25-28) are executed.

The following program uses 2 nested if-else statements to determine the larger of the three numbers:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#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:

1
2
Enter three numbers: 12 35 54
Largest number is 54

2nd run:

1
2
Enter three numbers: 77 23 871
Largest number is 871

Matching if.. else parts #

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

1
2
3
4
5
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 ({}).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
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 clause #

if-else is a bi-directional statement that is used to test a condition and take one of the possible two actions. What if we to perform a series of tests? One way to check for multiple conditions is to use the nested if-else statement. We have seen an example of this technique earlier in this chapter. Another way to accomplish this is to use the else-if clause. The else-if clause extends the basic if-else statement and allows us to perform a series of tests. The updated syntax of the if-else statement looks like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
if(condition1)
{
    statement1;
}

else if(condition2)
{
    statement2;
}

else if(condition3)
{
    statement3;
}

...

else
{
    statement4;
}

Here, each condition is checked one by one. As soon as a condition is found to be true then statements corresponding to that block are executed. The conditions and statements in the rest of the if-else statement are skipped and program control comes out of the if-else statement. If none of the conditions is true then statements in the else block are executed.

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

Let's rewrite the program to determine the largest of the two numbers using the else-if clause.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#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;
}

This version of the program is functionally equivalent to the one that uses nested if-else statement. But it avoids deep indentation making the code more readable.