Difference Between If-Else And Switch In C Programming

Introduction

In our daily lives, we make several decisions, like whether to eat pizza or pasta or a burger. The decision which we opt for often decides our future course of action. Like choosing a car over a bike while going to office cities like Bangalore would most likely make one stuck in huge traffic.

Decision-making is not only limited to the human paradigm but entered into the technological world. Eg - we train robots on which action to perform and which to avoid. The most famous example is Chitti in the movie Robot where a little change in chip code resulted in a robot destroying the city and making its own robot army.

If we talk in the coding world, we use conditional statements like if, else, else-if, or switch statements for making an informed decision.

Prerequisite

  • Basic understanding of C/C++
  • Understanding of conditional statements

Switch Statement

In this, the condition provided is checked with multiple identifiers i.e with multiple cases. If any given case comes out to be true, then the code corresponding to that specific case gets executed. If none of the cases becomes true, then the block of code corresponding to the default case gets executed.

switch (expression){
    case identifier1:
    //code block
    break;
    case identifier2:
    // code block
    break;
    ....
    case identifierN:
    //code block
    break;
    default:
    //code block
}

For a better understanding of the switch statement please refer to the below-given code.

Suppose you go to a concert and due to the huge crowd you are unable to see the staging area. The only thing you can hear is the song. On the basis of the song, you know the singer. Let's code the given situation with the help of a switch statement.

Here we are taking a string ‘song’ that represents the song played during the concert and printing the singer accordingly.

switch (song){
    case “Attention”:
    cout<<"singer is Charlie Puth"<<endl;
    break;

    case “Yaarr Ni Milyaa”:
    cout<<"singer is Hardy Sandhu"<<endl;
    break;

    case "Tu hai ki nahi":
    cout<< "singer is Ankit Tiwari"<<endl;

    default:
    cout<< "wrong input entered "<<endl;
}

Here you can see that after every case break statement is given in order to avoid a clash between 2 sets of code blocks.

If we do not provide a break statement then the control of the program will execute all the code blocks until it encounters a break statement, with the exception of the default case.

switch (song){
    case “Attention”:
    cout<<"singer is Charlie Puth"<<endl;

    case “Yaarr Ni Milyaa”:
    cout<<"singer is Hardy Sandhu"<<endl;
    break;

    case "Tu hai ki nahi":
    cout<< "singer is Ankit Tiwari"<<endl;

    default:
    cout<< "wrong input entered "<<endl;
}

In the above case, if the song is “Attention” then the system should print “singer is Charlie Puth”. However as a break statement is given after that, thus the system would also print “singer is Hardy Sandhu” which is wrong as it has nothing to do with that song.

However, in some instances, avoiding the break statements is suitable. Suppose we have to print months' names having 31 days, then we have to multiple months thus in such a situation break statement can be avoided.

If -else statement

If else statement provides another means through which users can make informed choices. In this, a given condition is checked, and if the given condition comes to be true then control of the program goes to one part of a block and executes statements mentioned in the ‘if’ block. But if the condition comes to be false then control of the program execute the statement mentioned under else block

On understanding, the basics let us further hone our knowledge through an example.

Suppose in the classroom you are advised to choose a number. If the number falls in the range of [2,6] then you have to perform task 1, if it falls in the range [7,10] then perform task 2 and otherwise perform task 3.

Then the code for the same would like,

# include <iostream>
using namespace std;

int main {
  int N;
  cin >>N;
  if (N >=2 && N<=6){
  cout<<"perform task 1"<<endl;
  }else if (N >=7 && N<=10){
    cout <<"perform task 2"<<endl;
  }else{
    cout<< "perform task 3"<<endl;
  }
  return 0;
}

Another example for the nested else-if statement.

Consider yourself to be in a country X where you become eligible for voting at age of 15, can contest for election at age of 32, and retire from the public and private sector at age of 65.

Then the given case can be coded using the if-else statement is given below,

# include <iostream>
using namespace std;

int main {
  int age;
  cin >> age;

  if (age >= 65){
    printf ("retire from public and private sector")
  }else if (age >= 32){
      printf ("yes now can contest for elections");
  }else if(age >= 15){
      printf("Wow, you can cast vote");
  }else{
      printf("you are too small even to vote");
  }
  return 0;
}

Comparison between if-else and switch statement

Similarities between if-else and switch statements,

  1. Both of them are used for controlling the flow of execution of the program
  2. Even though having differences in syntax, they both are employed for the same purpose

Difference between if-else and switch statement

Having seen some similarities between if-else and switch statements, let's look at some similarities between them.

  1. In the if-else statement, if the condition inside the if block comes to be false, then the code present in the else block gets executed. While in the switch statement, if no identifier satisfies the given condition then the code in the default block gets executed.

  2. It is making changes in the switch statements as they are easy to trace, while it is time-consuming in the if-else statement

  3. If-else statements are used to test both logical expressions and equality, while switch statement tests only for equality 

if (N >= 2 && N <= 5)
{
printf("N is between 2 and 5"); 
}
else
{
printf("N is outside the range of 2 & 5"); 
}
switch(N)
{
case 2: case 3: case 4: case 5: 
printf ("N is between 2 and 5"); 
break;

default:
printf("N is outside the range of 2 & 5");
}

Here to check whether falls in between 2 & 5 we have to check all equality conditions in the switch statement.

  1. In an if-else statement, it is possible to evaluate various types of variables like integer, character, floating type, pointers, or boolean type.

While switch statement presents some constraints as it can be used for character expression or integer types.

  1. The speed of execution in the switch statement is faster than an if-else statement. If the user has to implement several options, then the speed of execution in the if-else statement is slower than the switch statement.

Conclusion

In this article, we gained a basic understanding regarding if-else and switch statements and their usage. Along with we have seen similarities and differences among them. To wrap it all:-

It is up to the programmer whether to use an if-else statement or switch statement as both of them serve a similar purpose. Both of the statements have some advantages over others.

To further enhance your knowledge on if-else and switch statements, the intuition behind how it works, and its usage in various competitive platforms like CodeChef with beautiful schematics, one may want to have a look at this curated article published on the Difference Between if-else and Switch on Scaler topics.

To further enhance your knowledge on C programming read these important articles:

  1. C Program to Find LCM of two Numbers
  2. C Program to Find Transpose of a Matrix
  3. Download and Install C/GCC Compiler for Windows
  4. C Program to Multiply Two Matrices

Happy Learning!


Similar Articles