C – Switch Case

Switch:

  • It is a conditional statement that executes specific set of statements(case) based on given choice.
  • Default case executes if the user entered invalid choice.
  • Case should terminate with break statement.

Syntax:

switch(choice)
{
	case 1 :  Statements ;
		  break
	case 2 :  Statements ;
		  break
	......

	case n :  Statements ;
		  break
	default: Statements ;
}

FlowChart:

#include<stdio.h>
int main(){
            char ch;
            printf(“Enter character(r, g, b) : “);
            scanf(“%c”, &ch);
            switch(ch)
            {
                        case ‘r’ :            printf(“Red \n”);
                                                break;
                        case ‘g’ :           printf(“Green \n”);
                                                break;
                        case ‘b’ :           printf(“Blue \n”);
                                                break;
                        default :          printf(“Unknown \n”);
            }
            return 0;
}

Program to perform arithmetic operations based on given choice:

#include<stdio.h>
int main()
{
            int a, b, c, ch;
            printf(“Arithmetic Opeations”);
            printf(“1.Add \n”);
            printf(“2.Subtract \n”);
            printf(“3.Multiply \n”);
            printf(“4.Divide \n”);
           
            printf(“Enter your choice : “);
            scanf(“%d”,&ch);
           
            if(ch>=1 && ch<=4)
            {
                        printf(“Enter 2 numbers : \n”);
                        scanf(“%d%d”, &a, &b);
            }
 
            switch(ch)
            {
                        case 1: c=a+b;
                        printf(“Add result : %d\n”, c);
                        break;
                       
                        case 2: c=a-b;
                                    printf(“Subtract result : %d\n”, c);
                                    break;
                       
                        case 3: c=a*b;
                                    printf(“Multiply result : %d\n”, c);
                                    break; 
                       
                        case 4: c=a/b;
                                    printf(“Division result : %d\n”, c);
                                    break;
                       
                        default:printf(“Invalid choice\n”);        
            }
}
Scroll to Top