Switch statement is used to solve multiple option type problems for menu like program, where one value is associated with each option. The expression in switch case evaluates to return an integral value, which is then compared to the values in different cases, where it matches that block of code is executed, if there is no match, then default block is executed. The general form of switch statement is,
switch(expression) { case value-1: block-1; break; case value-2: block-2; break; case value-3: block-3; break; case value-4: block-4; break; default: default-block; break; }
Points to Remember
- We don't use those expressions to evaluate switch case, which may return floating point values or strings.
- It isn't necessary to use break after each block, but if you do not use it, all the consecutive block of codes will get executed after the matching block.
int i = 1; switch(i) { case 1: printf("A"); // No break case 2: printf("B"); // No break case 3: printf("C"); break; }
Output : A B C
The output was supposed to be only A because only the first case matches, but as there is no break statement after the block, the next blocks are executed, until the cursor encounters a break. - default case can be placed anywhere in the switch case. Even if we don't include the default case switch statement works.
Example of Switch Statement
#include<stdio.h> #include<conio.h> void main( ) { int a,b,c,choice; clrscr( ); while(choice!=3) { printf("\n 1. Press 1 for addition"); printf("\n 2. Press 2 for subtraction"); printf("\n Enter your choice"); scanf("%d",&choice); switch(choice) { case 1: printf("Enter 2 numbers"); scanf("%d%d",&a,&b); c=a+b; printf("%d",c); break; case 2: printf("Enter 2 numbers"); scanf("%d%d",&a,&b); c=a-b; printf("%d",c); break; default: printf("you have passed a wrong key"); printf("\n press any key to continue"); } } getch(); }
No comments:
Post a Comment