Showing posts with label 9.3.4 Switch Statement. Show all posts
Showing posts with label 9.3.4 Switch Statement. Show all posts

Monday, August 31, 2020

9.3.4 Switch Statement

Switch Statement in C.

  • The switch statement is similar to if statement but case check is done instead of checking the condition. 
  • When you come to a particular case, you write the statements that you want to execute inside the case. 
  • Case is matched to an integer variable. 
  • The same case goes to the execute case which matches the integer variable
Syntax :-


int caseNumber = n;
switch(caseNumber)
{
case 1:
/* Statements to be executed if caseNumber is 1 */
break;
case 2:
/* Statements to be executed if caseNumber is 2 */
break;
default:
/* Statements to be executed if caseNumber is not 1 & 2 */
break;
}


  • When you set the caseNumber variable with an integer value and pass it in the switch statement, the same number that matches this number will be executed.
  • For example, if you have passed 2 in case number then the case of second number will execute and all statements before the break will be executed.
  • If a case does not match then the default case is execute. 
  • If after each case the break statement is used then all the cases will be executed.
  • You can also define the case with alphabets.

EXAMPLE :-


// Switch Statement in C.
#include <stdio.h>
void main()
{
int caseNumber;
printf("Enter a number : ");
scanf("%d",&caseNumber);
/* Passing the case number to switch to execute desired case */
switch(caseNumber)
{
case 1:
printf("\n First Switch Case executed..");
break;
case 2:
printf("\n Second Switch Case executed..");
break;
case 3:
printf("\n Third Switch Case executed..");
break;
case 4:
printf("\n Fourth Switch Case executed..");
break;
default:
printf("\n You can only enter 1,2,3 and 4");
break;
     }
}


OUTPUT

Third Switch Case executed..