C

Simplified tutorials to learn the popular basic language C

VB.Net

Learn the basic desktop development application language

CodeIgniter

One of the popular PHP three tier (MVC) framework

Switch Statement in C with Example


Abstraction:
        This lesson teaches you the working of Switch Statement and its working with examples



           Switch statement is an interesting decision statement in C programming. This statement tests the value of given variable or expression against list of case values and when a match is found, a block of statement associated with this case will be executed.

General form of switch statement:


Switch(expression)
{
  case 1:
             block 1;
             break;
  case 2:
             block 2;
             break;
  case 3:
             block 3;
             break;
  ……………………  
  ……………………   
  default:
             default block;
             break;
}

Let us learn more with an example:

This program checks the given number is 1 or 2 or 3:
  
#include<stdio.h>
#include <conio.h>
int main()
{
  int nmbr;
  printf("Enter a number: ");
  scanf("%d",&nmbr) ;
  switch(nmbr)
   {
   case 1:
     printf("One");
     break;
   case 2:
    printf("Two");
    break;
  case 3:
    printf("Three");
    break;
  default:
   printf("Number is not 1,2 or 3");     
   break;
  }
getch();
}

Explanation:
  • scanf("%d",&nmbr) ;
Read a number to the variable ‘nmbr’.
  • switch(nmbr)
The given number is inside the switch statement. Now we can check the given number with a block of statement.
  • case 1:
        printf("One");
        break;
if the given number is ‘1’ then the printf block [ printf("One"); ] works and shows ‘One’ on the screen. After the end of every block, we should use ‘break;’.
  • case 2:
       printf("Two");
       break;
    case 3:
       printf("Three");
       break;
Both case 2 and case 3 work like case 1.
  • default:
         printf("Number is not 1,2 or 3");
         break;
This block is the default block, that is if the given number is other than 1, 2 or 3, then this default block will work. Here default statement contains a print statement. [ printf("Number is not 1,2 or 3"); ]

Sample Output:


Note: Here we check the given number with another number. In case of character, we have to use single quotes. See this example;

Check whether given character is a or b:

#include<stdio.h>
#include <conio.h>
int main()
{
 char ltr;
 scanf("%c",&ltr) ;
 switch(ltr)
   {
     case 'a':
        printf("Given letter is a");   
        break;
     case 'b':
       printf("Given letter is b");
       break;
    default:
       printf("Other than a or b");   
       break;
    }
getch();
}

Explanation:

This program is like the first example program. If the given character is ‘a’ or ‘b’ then the corresponding block work else the default block will be work. In case of character types, single quotes used.  Eg: case ‘a’.

No comments:

Post a Comment