Switch Case Statement - C Language Tutorial [C Programs]

Description

Switch case statement is used when user has multiple alternative of codes to choose, depending upon the value of single variable.

Syntax

  1. switch (integer expression or integer or character variable)
  2. {
  3. case 1:
  4.   statement;
  5.   statement;
  6.   break;
  7. case 2:
  8.   statement;
  9.   statement;
  10.   break;
  11. case 3:
  12.   statement;
  13.   statement;
  14.   break;
  15. default:
  16.   statement;
  17. }


In the above syntax after case keyword constant (1, 2, 3) is considered as integer it may be character too.

First integer expression is calculated then the value of integer or character is matched one after another with constant values of case statements. When a match is found then that case section of code is executed and if no match is found then default keyword code is executed.

Switch variable and case constant variables should be of same data type.
Value of switch variable should be assigned before entering the switch case.
Each case keyword is followed by a constant and a colon.
Every case section should end with break statement to end the switch case else it enters into the next case.

Source code

  1. //Using switch case statement
  2. #include <stdio.h>
  3. #include <conio.h>
  4. void main()
  5. {
  6. int choice;
  7. clrscr();
  8. printf("Select any option number from 1 to 4 : ");
  9. scanf("%d",&choice);
  10. switch(choice)
  11. {
  12. case 1:
  13. printf("You have selected first option");
  14. break;
  15. case 2:
  16. printf("You have selected second option");
  17. break;
  18. case 3:
  19. printf("You have selected third option");
  20. break;
  21. case 4:
  22. printf("You have selected fourth option");
  23. break;
  24. default:
  25. printf("Invalid option selected");
  26. break;
  27. }
  28. getch();
  29. }

Program working steps

First line of the program is the comment, 2nd and 3rd line is about preprocessor directive included in the program.
void main() function from where the program execution starts.
Variable declaration int choice and clrscr() function to clear the screen.
Program asks the user to enter any number from 0 to 4, After entering the number program stores the value to variable choice.
Switch statement variable value(i.e. choice) is compared with constant values followed by the each case statements. When a match is found then the program executes the statements from that particular case and breaks the switch loop. And if no match is found it executes the default keyword statement and terminates the switch loop.
Eg: If user enters 2 then the output will be 'You have selected second option'.
getch() function to avoid flash up and exit off console screen.


Thank you for sharing Your Knowledge with others who need It.-Team LetML

Post a Comment

Copyright © LetML. Blogger Templates Designed by OddThemes