Selection Statement In C: Switch Case Explanation With Examples


Selection Statement In C

Selection statement allows programmer to run particular flow on the basis of choice. User provides choice and it matches with a list of choices and on the basis of equality output comes.

The “switch”, “case”, “otherwise” and “break” are the selection statement keywords. 

1. Simple Use Of Switch Case

2. Multiple Switch Case

3. Nested Switch Case

4. Conditional Switch Case/Use Of Logical Operators With Switch Case

Simple - Switch Case

Switch case deals with user’s selection, and after that associated flow will be executed.
     
Points To Be Noted –

Switch statement expression should be integral (numeric) or enumerated (example: enum, will it discuss later)  values. Switch can have any number of case statements.

Case statement is associated with constant values and it will followed by ":" .
case expression’s data-type and switch expression’s data type should be same.

Break statement is optional but its good practice to have it after each case statement. If don’t use break, program will go through with all cases until breaks is found.

Default does not need break as it executes when there is no case matches.It is also optional.

Syntax : -


switch (choice) {


case constant-1:

break;            // Optional


case constant-2:

break;            // Optional


case constant-3:

break;            // Optional


default:          // Optional

}

#Program 1

Write a program to perform calculator operations on two numbers.

Operation,

1 = add two numbers

2 = subtract two numbers

3 = multiply two numbers

4 = divide two numbers

If operation is out of 1, 2, 3 and 4 then display message “Invalid operation”

#include <stdio.h>


void main() {


int num1,num2,opertaion,result;


printf("Enter 1st number");

scanf("%d",&num1);

printf("\nEnter 2nd number");

scanf("%d",&num2);

printf("\nSelect calculator operation from 1, 2 ,3 and 4");

scanf("%d",&opertaion);


switch (opertaion) {


  case 1:

  result = num1 + num2;

  break;


  case 2:

  result = num1 - num2;

  break;


  case 3:

  result = num1 * num2;

  break;


  case 4:

  result = num1 / num2;

  break;
   

  default: 

  printf("\nInvalid operation"); 

}

printf("\nResult of the operation %d",result);

}

Multiple - Switch Case

Switch case statement can be use as multiple level. Once first switch ends programmer
can go with another switch case statement. It is called multiple switch statement.

Syntax : -


switch (choice1) {


case constant:

break;            


default:          


} 

switch (choice2) {


case constant:

break;  
          

default:          

} 


#Program 2

Write a program to enter student name,rollNo and marks in subject (math,science and english)

Ask user to press choice 1, 2 or 3, 

1 =  for total marks.

2 = for percentage

3 = division (A,B,C and D)

if choice does not match ask user to press again.

Apply another switch case on division

A = First division

B = Second division

C = Third division

otherwise = Fail


#include <stdio.h>


void main() {


char name[10],division;

int roll_no,percentage,math,science,eng,total,option;


printf("Enter student name");

fgets(name,10,stdin);

printf("Enter roll no");

scanf("%d",&roll_no);

printf("Enter marks in math,science and english");

scanf("%d%d%d",&math,&science,&eng);

printf("Enter option from 1,2 and 3");

scanf("%d",&option);


total =math+science+eng;

percentage = (total*100)/300;


switch(option) {


case 1:

printf ("total marks - %d",total);

break;


case 2:

printf ("percentage - %d",percentage);

break;


case 3:


if(percentage>=60)


division ='A';


else if (percentage>=45 && percentage<60)


division = 'B';


else if (percentage>=33 && percentage<45)


division = 'C';

else


division = 'D';

break;


default:

printf("Invalid option, please try again");

}


if (division!='\0') {


switch (division) {


case 'A':

printf("\nFirst division");

break;


case 'B':

printf("\nSecond division");

break;


case 'C':

printf("\nThird division");

break;


default:

printf("\nFail");


}

}

}

Note: if (division!='\0') tells do checking with switch case if division is not null. '\0' means null character.
           
Nested - Switch Case

While programming one switch case can have another switch case statement.One switch statement inside another is known as nested switch statement.

Syntax : -


switch (choice) {


case constant:


switch (nested_choice) {


case constant:

break;               


default:            

}

break;            


default:          

} 


#Program 3

Write a program to ask number of sides of any shape from user and print the shape name.

number_of_sides,

3 = Triangle

4 = There are more then 1 shapes having 4 sides, tell user to press 1,2 or 3 and display different shapes name. 

5 = Pentagon
6 = Hexagon

8 = Octagon

If sides does not match then display message "No match found, please try again"

#include <stdio.h>


void main() {


int sides,choice;


printf("Enter sides of any shape");

scanf("%d",&sides);


switch(sides) {


case 3:

printf("It is triangle");

break;


case 4:

printf("Please enter your choice from 1,2 and 3");

scanf("%d",&choice);

 
switch (choice) {    // Nested switch case


case 1:   

printf("It is rectangle");

break;


case 2:

printf("It is square");

break;


case 3:

printf("It is trapezoid");

break;               

}

break;


case 5:

printf("It is pentagon");

break;


case 6:

printf("It is hexagon");

break;


case 8:

printf("It is octagon");

break;


default:

printf("No match found, please try again");

 
 }

}

Conditional - Switch Case

Till now you have seen that if switch's expression or variable value matches with case value then particular flow executes. We have defined constant value at compile-time to check equality but this constant value may come at run-time as well on basis of some conditions.

Here we will learn how to use conditional/logical operators with switch case.

To apply conditions with switch case, ternary operators will help us. 

#Program 4

Write a program to execute switch case specially for specific choice.

#include <stdio.h>


void main() {


int option;


printf("Please Enter Any Number In Between 10 - 20");

scanf("%d",&option);


switch(option>=10 && option<=20 ? option : -1) {


case -1:

printf("Invalid Number.");  

break;


case 4:

printf("Welcome To 4th Level");

break;


case 15:

printf("Welcome To 5th Level");

break;


case 8:

printf("Welcome To 8th Level");

break;


default:

printf("No match Found,Please Try Again");

}

}


Thanks for reading, please do share and comment your suggestions.

No comments

Powered by Blogger.