Using Switch Case

By this time, you must be tired of writing if-else statements. It must be very tiring to write many if statements, so that you may check each if statement with one integral value. For example, if we had 10 different numbers and a print statement associated with each of these 10 numbers, then you need to write 10 different if statement, or a rather large if statement syntax, which can get confusing also at some times. But, here in this note, we are going to see a better programming approach to deal with this situation. We will see, what is known as "Switch Statement" in the programming language world. 

A Switch Statement is useful when you want to have a variable checked for equality against a list of values. Each of the values, for which the variable is to be checked is termed as a 'case', and each of the checkings is called a switch case. 

So, let's just dive into the practical stuff now. 

First, let's see the syntax for a switch statement. 

switch(variable)

{

case possible_value1:

statements to be executed for possible_value1

break;

case possible_value2:

statements to be executed for possible_value2

break;

default:

If none of the options match, then default statement is executed.

}

Now, there are a few things that you should keep in mind while using a switch case. 

  1. The variable must be of an integral or a class type. 
  2. Any number of switch statements are allowed. 
  3. The date type of the variable and the possible values should be the same. 
  4. Break statement, quits the checking, and lets you out of the switch case. 
  5. Break statement is not complimentary, and therefore, if there is no break statement, then the checking will not stop, and it will check uptill the default value. 
  6. Default case is for such situations, where none of the possible values match. 

So, lets just take an example out here. Say, there is a class test, and the possible values be 0,1,2,3,4,5 out of total marks 5. 

#include<stdio.h>

int main()

{

int marks;

printf("Enter the marks \n");

scanf("%d",&marks);

switch(marks)

{

case 1:

printf("You got 1 mark");

break;

case 2:

printf("You got 2 mark");

break;

case 3:

printf("You got 3 mark");

break;

case 4:

printf("You got 4 mark");

break;

case 5:

printf("You got 5 mark");

break;

default:

printf("Marks Entered is wrong");

}

return 0;

}

When the above code is compiled or executed, the output looks like this: 

Enter the Marks

3

You got 3 mark

 

Switch Case basically lessens your work, when you have a lot of possible values to work with. Using switch cases will make your code more redundancy proof, and more optimised. 

Contributor's Info

Created:
0Comment