Tuesday 1 October 2013

Switch case in C

Loops                                                                                                                                    pointer

Switch:- Selecting only one alternative from multiple alternative .it is the advanced use of if else .
for providing multiple conditions we use switch case because using switch is more easier than if else.

EX:-

int i ,j , k,l;
printf("enter the vlaue of i and j");
scanf("%d%d",&i,&j);
printf("enter the operator +  -  *  \");
scanf("%d",&k);
switch(k)
{
case '+':
l=i+j;
printf("%d",l);
break;
case '-':
l=i-j;
printf("%d",l);
break;
case '*':
l=i*j;
printf("%d",l);
break;
case '\':
l=i\j;
printf("%d",l);
break;
default:
printf("enter valid operator");
break;
}


in cases we provide the condition.
the value in switch matches with cases. the case which have same value as the switch will execute.
if the value of switch does not match with any cases then it executes default.
we use break in all cases by which the cursor jump out from the body.

if we does not use break in the cases then it executes all the cases.

EX :-
int i ,j , k,l;
printf("enter the vlaue of i and j");
scanf("%d%d",&i,&j);
printf("enter the operator +  -  *  \");
scanf("%d",&k);
switch(k)
{
case '+':
l=i+j;
printf("%d",l);
case '-':
l=i-j;
printf("%d",l);
case '*':
l=i*j;
printf("%d",l);
case '\':
l=i\j;
printf("%d",l);
default:
printf("enter valid operator");
}

it executes all the cases


No comments :

Post a Comment