C If and Switch Case Examples (if, if else, if else if, nested if)

by Himanshu Arora on January 23, 2013

Control conditions are the basic building blocks of C programming language. In this tutorial, we will cover the control conditions through some easy to understand examples.

There are two types of conditions :

  • Decision making condition statement
  • Selection condition statement

Let’s understand these two types with the help of examples.

Decision making condition statement

Conditions like ‘if’, “if-else”, “if-else-if”, “nested if”, ternary conditions etc fall under this category.

1. If Condition

This is basic most condition in C – ‘if’ condition. If programmer wants to execute some statements only when any condition is passed, then this single ‘if’ condition statement can be used. Basic syntax for ‘if’ condition is given below:

if (expression) {
    Statement 1;
    Statement 1;
    ..
    ..
}

Now, we should have working program on ‘if’ condition.

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
if (argc != 2) {
    printf("Can not execute, command line argument expected by Program\n");
    exit(0);
}
return 0;
}

Output for above program is given below.

$ ./if_cond
Can not execute, command line argument expected by Program

In above program, programmer wanted to exit from program if two command line arguments are not passed to program. We can see if program executable is run without any argument, message is displayed on console and program exited.

2. If-Else Condition

This is two-way condition in C – ‘if-else’ condition. If programmer wants to execute one set of statements on success case of one condition and another set of statements in all other cases, then ‘if-else’ condition is used. Either ‘if’ case statements are executed or ‘else’ case statements are executed. Basic syntax for ‘if-else’ condition is given below:

if (expression1) {
    Statements;
} else {
    Statements;
}

Now, given below is very basic program that has been made for checking number is even or odd, it is for understanding usage of ‘if-else’ condition.

#include <stdio.h>
int main(int argc, char *argv[]) {
int num;
printf("\nEnter any number to check even or odd :");
scanf("%d", &num);
if (num%2 == 0) {
    printf("%d is EVEN\n", num);
} else {
    printf("%d is ODD\n", num);
}
return 0;
}

Output:

$ ./if-else_cond

Enter any number to check even or odd :23
23 is ODD
$ ./if-else_cond

Enter any number to check even or odd :24
24 is EVEN

In above program, programmer wanted user to enter number which is checked in condition whether it is divisible by 2. If condition is true, number is displayed “EVEN”, otherwise number is displayed “ODD”.

3. Ternary Operator

There is alternative to ‘if-else’ condition which is ternary operator that is different syntax but provides functionality of ‘if-else’ condition. Basic syntax of ternary operator is given below:

Condition expression ? if condition TRUE, return value1 : Otherwise, return value2;

For example,

#include <stdio.h>
int main(int argc, char *argv[]) {
int num;
printf("\nEnter any number to check even or odd :");
scanf("%d", &num);
(num%2==0) ? printf("%d is EVEN\n", num) : printf("%d is ODD\n", num);
return 0;
}

Output:

$ ./a.out 

Enter any number to check even or odd :24
24 is EVEN
$ ./a.out 

Enter any number to check even or odd :23
23 is ODD

4. If-Else-If condition

This is multi-way condition in C – ‘if-else-if’ condition. If programmer wants to execute different statements in different conditions and execution of single condition out of multiple conditions at one time, then this ‘if-else-if’ condition statement can be used. Once any condition is matched, ‘if-else-if’ condition is terminated. Basic syntax for ‘if-else-if’ condition is given below:

if (expression1) {
    Statements;
} else if (expression2) {
    Statements;
} else {
    Statements;
}

Now, given below is very basic program that has been made for mapping user-input color with fruit, it is for understanding usage of ‘if-else-if’ condition.

#include <stdio.h>

int main(int argc, char *argv[]) {

char input_color[100] = {0};

printf("\nEnter color [red/green/yellow] to map with fruit :");
scanf("%s", input_color);

if (strncmp(input_color, "red", sizeof(input_color)) == 0) {
    printf("%s is mapped to APPLE\n", input_color);
} else if (strncmp(input_color, "green", sizeof(input_color)) == 0) {
    printf("%s is mapped to GRAPES\n", input_color);
} else if (strncmp(input_color, "yellow", sizeof(input_color)) == 0) {
    printf("%s is mapped to BANANA\n", input_color);
} else {
    printf("\nInvalid color entered :%s", input_color);
}

return 0;
}

Output:

$ ./if-else-if_cond 

Enter color [red/green/yellow] to map with fruit :green
green is mapped to GRAPES
$ ./if-else-if_cond 

Enter color [red/green/yellow] to map with fruit :yellow
yellow is mapped to BANANA
$ ./if-else-if_cond 

Enter color [red/green/yellow] to map with fruit :testcolor

Invalid color entered :testcolor

In above program, programmer wanted user to enter color (out of red/green/yellow as indicated), then input color is compared first with red in ‘if condition’, then compared with ‘else-if’ conditions. Here, it is noted that once any condition is matched, ‘if-else-if’ condition terminates. Here, if no ‘if’ or ‘else if’ is matched, then at last ‘else’ condition is executed which we can see in above output when invalid color is input.

5. Nested-If conditions

This is nested if or if-else or if-else-if conditions in C. Basic syntax for nested ‘if’ or ‘if-else’ condition is given below:

if (expression1) {
    Statements;
    if (expression2) {
        Statements;
    } else {
        Statements;
    }
}

Given below is basic program using nested if conditions.
#include <stdio.h>

int main(int argc, char *argv[]) {

int i = 5;
int *ptr = &i;
int **double_ptr = &ptr; 

if (double_ptr != NULL) {

    if (ptr != NULL) {
        printf ("Now safe to access pointer, ptr contains %d", *ptr);
    }
}
return 0;
}

Output:

$ ./a.out 

Now safe to access pointer, ptr contains 5

In above program, nested if conditions are used. It is always safer to have NULL check on pointer before accessing it (More on C pointers here).

In the above code snippet, example is taken for double pointer. The first ‘if’ condition is to check double pointer (i.e. ** double_ptr) is non-NULL, then only, move ahead to access inner pointer (i.e. ptr). If double pointer is non-NULL, then only nested ‘if’ condition is checked whether inner pointer is NULL or not. If nested ‘if’ condition is OK, then it is safe to access value at pointer.

Selection condition statement

6. Switch case conditions

Switch case is clean alternative of ‘if-else-if’ condition. Here, several conditions are given in cases that facilitates user to select case as per input entered. Basic syntax for using switch case statement is given below.

switch(expression) {
        case constant expression1:    
            statements1; break;
        case constant expression2:
            statements1; break;
         ..
         ..
        default : statementsN;
}

It is noted that any statement between switch statement and first case statement is dead code which is never executed. For understanding ‘switch’ case, basic program is created in which basic arithmetic operation on two numbers is done as per input entered by user. Several cases of arithmetic operations are handled in switch cases. Basic program using ‘switch case’ is given below.

#include <stdio.h>
int main(int argc, char *argv[]) {
char ch;
int num1, num2;

printf("\nBasic operation:");
printf("\nAdd [a]");
printf("\nSubtract [s]");
printf("\nMultiply [m]");
printf("\nDivide [d]");

printf("\nEnter character for operation:");
scanf("%c", &ch);

printf("\nEnter two numbers for operation:");
printf("\nEnter num1=");
scanf("%d", &num1);
printf("\nEnter num2=");
scanf("%d", &num2);

switch (ch) {
    case 'a':
        printf("\nAddition of num1 and num2=%d", (num1+num2));
        break;

    case 's':
        printf("\nSubtraction of num1 and num2=%d", (num1-num2));
        break;

    case 'm':
        printf("\nMultiplication of num1 and num2=%d", (num1*num2));
        break;

    case 'd':
        printf("\nDivision of num1 and num2=%d", (num1/num2));
        break;
    case 'x':
        printf ("\nTest switch case1");
    case 'y':
        printf ("\nTest switch case2");
    default:
        printf("\nInvalid value eneterd");
        break;
}
printf("\n");
return 0;
}

Output:

$ ./a.out 

Basic operation:
Add [a]
Subtract [s]
Multiply [m]
Divide [d]
Enter character for operation:a

Enter two numbers for operation:
Enter num1=10

Enter num2=5

Addition of num1 and num2=15
$ ./a.out 

Basic operation:
Add [a]
Subtract [s]
Multiply [m]
Divide [d]
Enter character for operation:d

Enter two numbers for operation:
Enter num1=10

Enter num2=5

Division of num1 and num2=2
$ ./a.out 

Basic operation:
Add [a]
Subtract [s]
Multiply [m]
Divide [d]
Enter character for operation:G

Enter two numbers for operation:
Enter num1=10

Enter num2=5

Invalid value entered

In above program, user is given basic menu with operations allowed in program. User is asked to enter initial character of displayed operations. User is asked to enter two numbers also on which selected arithmetic operation would be performed. After all input from user, program checks input with switch cases and executes statements under matched switch case; since break statement is there so only statements under matched case are executed.

Note that if break statement is not given in cases and any case is matched, then statements of below cases would also get executed even though below cases condition is not matched. We can understand this in given below output. Here, as per code, if ‘x’ is entered, then case ‘x’ is executed and there is no break statement so all cases below case ‘x’ are executed without any condition check on below cases.

$ ./a.out 

Basic operation:
Add [a]
Subtract [s]
Multiply [m]
Divide [d]
Enter character for operation:x

Enter two numbers for operation:
Enter num1=10

Enter num2=5

Test switch case1
Test switch case2
Invalid value entered

Linux Sysadmin Course Linux provides several powerful administrative tools and utilities which will help you to manage your systems effectively. If you don’t know what these tools are and how to use them, you could be spending lot of time trying to perform even the basic administrative tasks. The focus of this course is to help you understand system administration tools, which will help you to become an effective Linux system administrator.
Get the Linux Sysadmin Course Now!

If you enjoyed this article, you might also like..

  1. 50 Linux Sysadmin Tutorials
  2. 50 Most Frequently Used Linux Commands (With Examples)
  3. Top 25 Best Linux Performance Monitoring and Debugging Tools
  4. Mommy, I found it! – 15 Practical Linux Find Command Examples
  5. Linux 101 Hacks 2nd Edition eBook Linux 101 Hacks Book

Bash 101 Hacks Book Sed and Awk 101 Hacks Book Nagios Core 3 Book Vim 101 Hacks Book

{ 7 comments… read them below or add one }

1 Tim Hansell January 23, 2013 at 10:03 am

Your example for the ternary operator:

(num%2==0) ? printf(“%d is EVEN\n”, num) : printf(“%d is ODD\n”, num);

Could be rewritten in the following manner:

printf( “%d is %s\n”, num, ((num%2==0)?”EVEN”:”ODD”) );

To show the flexibility of the Ternary operator. As you showed it it is a mere syntactically different way to do the same thing, however the example above show some code re-use (one printf instead of 2, and using the return value of the ternary operator as a parameter to that printf)

Simply rewriting and IF-ELSE in the ternary operator syntax creates code that can be harder to read, whereas the rewritten example I included demonstrates the added functionality that the (?:) operator brings to the table that is not available from an IF-ELSE.

2 DuskoKoscica February 8, 2013 at 4:33 am

Two questions, I have seen that You try to be complete.
Now I have two questions. First is about ternary operator, cold yo have more of them in C, like in C++, and do you need the break thing all the time..

3 DuskoKoscica February 9, 2013 at 4:37 am

If not clear from abouve:
(a>b)? c=’p': (a<0) c='z' : c='m';

and, swithch dos not need the break all the time.

4 DuskoKoscica February 9, 2013 at 4:39 am

sorry I missed one ?, in the code above, my bad.
Could You find where Have I ommit the one ? in the code above….

5 Tim Hansell February 9, 2013 at 2:51 pm

I’m not sure I understand your question but…

The ternary operator means: THREE OPERANDS
So the syntax is:

?:

So you can’t just create one that has more than two actions. There is only a true action and a false action.

You can nest ternary operators, but there are potential typing problems with that.

6 duskokoscica February 11, 2013 at 8:20 am

Te Question is> Why You don’t make same chalanges, and some quiz just to see how people do understand.
Some more difficull samples….

Ok

7 babu December 3, 2014 at 3:52 am

When to use If-else if-else over switch statments and vice versa [duplicate]

Leave a Comment

Previous post:

Next post: