C Decision Making Control Structures - 'if', 'if - else', nested 'if', 'switch'

    0 Votes


As discussed earlier in previous chapters of this C programming tutorial, different relational and logical operator checks if the relation between the operands is correct or not and return true and false value based on the result of comparison. What if you want to do some operations based on the result of these comparisons? Or what if you want to repeat some operations until a condition is met? C has different control structures available to help this situation.

In C, we have two types of control structures. One is called branching and the other is called looping. We will discuss about the looping control structures in the next chapter of this tutorial. In this chapter let's look into different decision making control structures.

Decision Making Control Structures

Decision making control structures check one or multiple conditions and executes a group of statements if the conditions are evaluated to true and executes another group of statements if the conditions are evaluated to false. C has following decision making control structures:

  1. 'if' statement
  2. 'if ... else' statement
  3. Nested 'if ... else' statement or 'if ... else if... else' statement
  4. 'switch' statements

'if' Statement

Simplest control structure available in C is 'if' statement. The 'if' control structure consists of 'if' statement followed by an expression enclosed in parentheses. The 'if' statement evaluates the expression and if it evaluates to true, it will result in execution of immediate expression/statement following. Syntax of 'if' statement is given below.

if(expression)
	statement

The statement 'statement' will be executed if the 'expression' is evaluated to true. If the 'expression' is evaluated to false, 'statement' will not be executed.

The above syntax allows only execution of the immediately following statement. What if you want to execute more than one statement based on the evaluation of condition? In that case the set of statements that you want to execute needs to be enclosed in curly braces as given below.

if(expression)
{
    statement1
    statement2
    ..
    ..	
    statementN
}

It is good practice to enclose the statements you want to execute in braces even if there is only a single statement to be executed. This clears the confusion of which statements are executed if the expression of an 'if' statement is satisfied.

Also Read - Top C Interview Questions and Answers for Freshers & Advanced C Interview Questions and Answers

An important thing to remember while using 'if' statement is that every expression always return either true or false (0 is considered as false and others are considered as true), even assignment statement inside the conditional expression will not throw any compilation error. Sometimes programmers may mistakenly write if (a = 10) instead of if (a == 10). In this case, first the value '10' will be assigned to variable 'a' and then 'a' is tested to see if it's zero (false) or non-zero(true). So the 'if' statement block will always be executed no matter what the value of 'a' and to worsen things this will not generate any compilation error. To avoid this problem, it's better to use if (0 == a) instead of if(a == 0), as forgetting one '=' in the first case will produce compilation error

Example of 'if' Statement

The program given below checks if a number is positive number.

#include <stdio.h>
 
int main(void) {
    int i = 10;
    if (i > 0) {
        printf("%d is positive number", i);
    }
    return 0;
}

Output:
10 is positive number

'if else' Statement

Sometimes using only 'if'statement is not enough. Suppose we have a program to print whether the input number (say variable 'i') is odd or even. The decision part of the program is as follows

if ((i % 2) == 1)
{
    printf("Odd");
}

This way we can decide whether the number is odd or not. But to decide whether it is even, we have to again write almost same expression with changing the value 1 to 0. But C provides us a different solution to reduce the number of lines of codes that you need to write. It is called 'if ... else' statement, which is used to handle the false case of the 'if' expression.

Syntax of 'if ... else'statement is as given below:

if (expression)
{
    statement block1
} else {
    statement block2
}

In the above syntax, if the 'expression' evaluates to true, 'statement block1' will be executed. If the 'expression' evaluates to false, 'statement block2' will be executed.

Example of 'if-else' Statement

Using 'if ... else'statement we can write code to check a number is even or odd as given below.

#include <stdio.h>

int main(void) {
    int i = 10;
    if ((i % 2) == 1)
    {
        printf("%d is odd number", i);
    } 
    else
    {
        printf("%d is even number", i);
    }
    return 0;
}

Output:
10 is even number

Multi-way decision

We learnt in the previous section of this tutorial that, if-else statement is good for situations when you want to execute two different set of statements based on the result of a test expression. But what if we need to execute different sets of statements based on evaluation of more than one test expression? Will it be possible to express this situation with if-elseonly ? C has a great solution for this situation, called multi-way decision. Control structures with multi-way decision allow us to cover more than two possibilities. There are two options in which we can implement multi-way control structures in C. They are

  1. Nested 'if' statements or 'if...else if...else' statements
  2. 'switch' statements

Nested 'if' Statements or 'if...else if...else' Statements

Nested 'if' statement is similar to 'if-else' statement with the addition of more than one 'if-else'block. The syntax is given below.

if (expression 1)
{
    statement block 1
}
else if (expression 2)
{
    statement block 2
}
...
...
else if (expression n)
{
    statement block n
}
else
{
    statement block n+1
}

While executing nested 'if' statement, first 'expression 1' will be checked and if it evaluates to true 'statement block1' will be executed. If it is false, then 'expression 2' will be tested and it proceeds further in the same fashion.

Example of Nested 'if' Statement

Below program checks if a given number is positive, negative or zero using using nested 'if'statement.

#include <stdio.h>

int main(void) {
    int i = -1;
    if (i == 0)
    {
        printf("%d is zero", i);
    } 
    else if (i > 0)
    {
        printf("%d is positive", i);
    }
    else if (i < 0)
    {
        printf("%d is negative", i);
    }
    return 0;
}

Output:
-1 is negative

Also Read - Top Embedded C Interview Questions and Answers & C++ Interview Questions and Answers

'switch' Statements

The alternative of nested 'if' statement is called 'switch' statement, which has different statement blocks for different cases. Basically 'switch' statement tries to match evaluated value of an expression against different cases. Syntax of 'switch' statement is as follows.

switch(expression)
{
    case value 1:
        statement block 1;
        break;

    case value 2:
        statement block 2;
        break;

    ...
    ...

    case value n:
        statement block n;
        break;

    default:
        default statement block;
        break;
}

The expression 'expression' is evaluated first and the value is checked with different case values (value 1, value 2, ... etc. If one of the case values matches the result of expression, then respective statement block is executed. If none is matched, then the statement block of 'default' case is executed. You may notice another keyword in the switch statement which is break. If break keyword is omitted, all the the statements after that will be executed even if the corresponding case values do not match the value of expression. This is called a 'fall through' statement. For example, if 'break' is omitted and say, case 'value 1' is matched, then after execution of 'statement block 1' the code will execute statement block 2, 3 and so on until a 'break' statement is reached.

Rules for Writing 'switch' Statements in C Language

  • The values of case label must be unique, else complier will throw error
  • The values of case should be an integral constant (integer or character). If any variable is specified as part of a case, compiler will throw error, but a 'const' variable is allowed.
  • The 'default' case is optional and it can be placed anywhere in the switch block.
  • 'switch' statements can be nested; that means you can have another 'switch' statement as part of a statement block associated with a case.
  • The statement block of a case is optional and it can be shared by more than one cases.

Example of 'switch' Statement

We can rewrite the program to check if a number is even or odd using switch statement as given below.

#include <stdio.h>

int main(void) {

    int i = 5;
	
    switch(i % 2)
    {
        case 0:
            printf("%d is even number", i);
            break;

        case 1:
            printf("%d is odd number", i);
            break;
		
        // We do not need default case here as there can only be two cases 0 or 1.
    }	
    return 0;
}

Output:
5 is odd number

Related Articles

C Overview and Basic Syntax
Data Types in C Language
C Qualifiers - Constant and Volatile type Qualifier
C Type Casting with examples - float to int / int to char / int to long
C Constants and Literals
C Operators - Arithmetic, Assignment, Relational and Logical
C Operators - Bitwise Operators and Conditional Operators
C Operator Precedence and Associativity Table with Examples
C Input and Output Statements
C Format Specifiers for printf and scanf
Loops in C - for, while and do...while Loops
C 'break', 'continue' and 'goto' Statements to Control Program Flow
C Preprocessor Directives and Macros
C Functions Tutorial with Examples
C Arrays - Dynamic, 2d and Multidimensional with Examples
C Strings - Internal Working and Functions with example
C Pointers basics explained with examples
Structures in C Programming with Example
Unions in c programming with example
C Storage Class Specifiers - auto, register, static and extern

Popular Videos

How to speak to people

How to speak so that people want to listen.

Got a tip or Question?
Let us know