Translate

Saturday, May 9, 2020

The Switch Statement

Instead of using the if-else-if Ladder control statement, the Switch Statement is available in program C for Handling multiple choices. In Switch statement three keywords are used switch, case, and default.we can use integer. constant. but we can not use floating point and string constants.
Syntax:
Switch(expression)
{
  case constant 1:
  statement;
  break;
  case constant 2:
  statement;
  break;
  case constant 3:
  statement;
  break;
  default;
  statement
}

Flowchart:


Example:

#include<stdio.h>
#include<conio.h>
void main()
{
    int ch;
    printf("\nenter 1 for print red \nenter 2 for print blue  \nenter 3 for print green \nenter your choice");
    scanf("%d",& ch);
    
    switch(ch)
    {
        case 1:
        printf("red");
        break;
        
         case 2:
        printf("blue");
        break;
        
         case 3:
        printf("green");
        break;
        
        default:
        printf("wrong choice try again!");
        getch();
    }
}
    
Output:


    Here, you can See  the choice that is given by user is matched, one by one, when a match is found, the program executes the statements following case, and all subsequent case and default statement as well. If no match is found with any of the case statements, only the default statement is executed. 

No comments:

Post a Comment

C program to make a calculator using the switch statement.

/*perform arithmetic calculation on integers in C language*/ #include<stdio.h> #include<conio.h> void main() {     char op;     ...