Learn Switch Statement In C

Syntax:

switch(n)
{
case 1:

 //statement(s) to be executed if n=1;

break;

case 2:

 //statement(s) to be executed if n=2;

break;

default:
 statement(s);
}

Explanation of Syntax:

Switch,case,break,default are keywords. If value of n is 1 i.e n=1 then statements in case 1 are executed. Further cases are not executed as we used break keyword to prevent it from executing further cases.

If value of n does not matches any case then default is executed.

What is the use of switch statement?

According to definition on Wikipedia, in computer programming languages, a switch statement is a type of selection control mechanism used to allow the value of a variable or expression to change the control flow of program execution via a multiway branch.

Switch statement is used in programs whre you have to use menu i.e. in menu driven programs.

Example:

#include<stdio.h>

void main()
{
 int digit;

 printf("\n Enter any digit:- ")
 scanf("%d",&digit);

 switch(digit)
 {
 case 1: //If digit=1 then this case is executed
 printf("One");

 case 2: //If digit=2 then this case is executed
 printf("Two");

 case 3: //If digit=3 then this case is executed
 printf("Three");

 case 4: //If digit=4 then this case is executed
 printf("Four");

 case 5: //If digit=5 then this case is executed
 printf("Five");

 case 6: //If digit=6 then this case is executed
 printf("Six");

 case 7: //If digit=7 then this case is executed
 printf("Seven");

 case 8: //If digit=8 then this case is executed
 printf("Eight");

 case 9: //If digit=9 then this case is executed
 printf("Nine");

 case 0: //If digit=0 then this case is executed
 printf("Zero");

 default: //If you didn't entered a digit then this case is executed
 printf("\n You have not entered a single digit. \n");

 }

}

Explanation of Example:

Above program is simple program which prints or displays the given digit in word. If you entered a digit (say) 4, case 4 is executed in which we are printing the 'Four'. Similarly other cases get executed. If it is not a digit then default case is executed and corresponding message is printed.

Programs Based On Switch Statement:

  1. C program to perform different operation on two points
  2. C program to print number in word
  3. C program to perform arithmetic operations on two numbers
  4. C program to perform different operations on two numbers
  5. C program to accept radius from user and perform different operations on it
Prev - Nested If Else Next - Do While Loop

Comments