Académique Documents
Professionnel Documents
Culture Documents
case Statement
The if..else..if ladder allows you to execute a block code among many alternatives.
If you are checking on the value of a single variable in if...else...if, it is better to
use switch statement.
The switch statement is often faster than nested if...else (not always). Also, the
syntax of switch statement is cleaner and easy to understand.
Syntax of switch...case
switch (n)
case constant1:
break;
case constant2:
break;
default:
}
When a case constant is found that matches the switch expression, control of the
program passes to the block of code associated with that case.
The break statement is used to prevent the code running into the next case.
By if statement
#include<stdio.h>
main( )
{int x,y;
char z;
scanf("%c",&z);
scanf("%d",&x);
scanf("%d",&y);
if (z=='+'||z=='1')
printf("%d +%d=%d\n",x,y,x+y);
else if(z=='-'||z=='2')
printf("%d -%d=%d\n",x,y,x-y);
else if(z=='/'||z=='3')
printf("%d /%d=%d\n",x,y,x/y);
else if(z=='*'||z=='4')
printf("%d *%d=%d\n",x,y,x*y);
else printf("Error in choise");}
#include<stdio.h>
main( )
{ int x,y;
char z;
scanf("%c",&z);
scanf("%d",&x);
scanf("%d",&y);
switch(z)
{ case '+':
case '1':
printf("%d +%d=%d\n",x,y,x+y);
case '-':
case '2':
printf("%d -%d=%d\n",x,y,x-y);
break;
case '/':
case '3':
printf("%d /%d=%d\n",x,y,x/y);
break;
case '*':
case '4':
printf("%d *%d=%d\n",x,y,x*y);
break;
Example :
Write a c program to find currents for every switch case for the circuit shown
bellow
# include <stdio.h>
main ()
float v,r,i;
char s;
scanf("%c",&s);
scanf("%f",&v);
scanf("%f",&r);
switch(s)
printf("I=%f",i) ;
break;
printf("I=%f",i) ;
break;
printf("I=%f",i) ;
break;
printf("I=%f",i) ;
break;
}}