switch
statement :
Whenever
we want to check more possible conditions for a single variable a no. of
statements are necessary. C has a built-in multiway decision statement known as
a “ switch “ statement. The switch statement tests the value of a given
expression against a list of case values and when a match is found, a block of
statements associated with that case is executed.
In switch case
statement, no case can have two equal values. Default may appear at any place
and not compulsory. The flowchart and syntax of switch statement is shown below
:
Syntax : switch(expression)
{
case value-1:block-1;
break;
case value-2:block-2;
break;
case value-3:block-3;
break;
case value-n:block-n;
break;
default :block n+1;
}
statement-x;
Ex:
#include<stdio.h>
#include<conio.h>
void
main()
{
int a,b,c,choice;
clrscr();
printf(“Enter values of a and b:”);
scanf(“%d%d”,&a,&b);
printf(\n1.ADDITION\n2.SUBTRACTION\n3.MULTIPLICATION\n4.DIVISION
\n5.MODULo
DIVISION”);
printf(“\n select ur choice:”);
scanf(“%d”,&choice);
switch(choice)
{
case 1:c=a+b;
break;
case 2:c=a-b;
break;
case 3:c=a*b;
break;
case 4:c=a/b;
break;
case 5:c=a%b;
break;
default:printf(“\n Enter only a
valid choice”);
}
printf(“\nResult is = %d”,c);
getch();
}
Very informative blog!
ReplyDeletePlease take some time to visit my blog @
loop in C notes
Thanks!