Programming with C

⌘K
  1. Home
  2. Docs
  3. Programming with C
  4. Input/Output statements
  5. Decision making statement...
  6. Switch Statement

Switch Statement

Switch statement

  • A switch statement is used to control complex branching operations
  • When there are many conditions, it becomes too difficult and complicated to use if and if-else constructs.
  • In such case, the switch statement provides an easy and organized way to select among multiple operations, depending upon the outcome of a particular condition.

The general form of switch statement is

switch (expression)
{
    case constant1:
      // statements
      break;

    case constant2:
      // statements
      break;
    .
    .
    .
    default:
      // default statements
}

Flowchart

Example

Calculator Program using switch case

#include<stdio.h>
int main() 
{
    int choice;
    int num1,num2;
    printf("Enter two numbers \n");
    scanf("%d%d", &num1, &num2);
    printf("1.Addition\n");
    printf("2.Subtraction\n");
    printf("3.Multiplication\n");
    printf("4.Division\n");
    printf("Enter your choice\n");
    scanf("%d",&choice);
    switch(choice)
    {
        case 1: 
                printf("%d + %d = %d",num1, num2, num1+num2);
                break;
        case 2:
                printf("%d - %d = %d",num1, num2, num1-num2);
                break;
        case 3:
                printf("%d * %d = %d",num1, num2, num1*num2);
                break;
        case 4:
                printf("%d / %d = %.2f",num1, num2, num1/num2);
                break;
        default: 
                printf("ERROR:");
    }
    return 0;
}

Output

Enter two numbers
3 4
1.Addition
2.Subtraction
3.Multiplication
4.Division
Enter your choice
2
3 - 4 = -1

Views: 0

How can we help?

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments