V. Switch case statement
·
It is mainly used to match only character and
integer type value.
·
Its execution is fast rather than else if ladder
stmt.
·
It is generally used to create choice based
program.
·
We can not check condition like if condition.
syntax:
switch ( variable / constant /
expression )
{
case < value 1 > :
block of stmts;
break ;
case < value 2 > :
block of stmts ;
break ;
…
…
case < value n > :
block of stmts ;
break ;
default :
block of stmts ;
Note :-
a) Case keyword is used to specify value.
b) break keyword is optional which is used to terminate from switch stmts.
c) default is optional part. It will be executed if any case does not match.
Example 1:-
int digit =2;
swirch ( digit )
{
case 0 :
printf ( “ zero “);
break;
case 1:
printf( “ one “ );
break ;
.…
….
case 9 :
printf ( “ nine “ );
break ;
default :
printf ( “ Invalid digit “ );
}
Example 2:-
char ch = ‘E’ ;
switch ( ch )
{
case ‘A’ :
case ‘a’ :
case ‘ E’ :
case ‘e’ :
case ‘I’ :
case ‘I’ :
case ‘O’ :
case ‘o’ :
case ‘U’ :
case ‘u’ :
printf( “ vowel character “);
break ;
default :
printf( “ consonant character “ );
}
P1.Program to input two numbers and any arithmetic operator after that performed arithmetic operation using switch case statement.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int a , b;
char opt ;
printf( “ enter two numbers “ );
scanf( “ %d %d “, &a ,&b );
fflush (stdin);
printf ( “ Enter any arithmetic operator “ );
scanf( “ %c “, &opt);
switch ( opt )
{
case ‘+’ :
printf( “ Addition = %d “, a+b);
break;
case ‘-‘ :
printf( “ Subtraction = %d “, a-b);
break;
case ‘*’ :
printf( “ Multiplication = %d “ , a*b );
break;
case ‘/’ :
printf( “ Division = %d “, a/b );
break;
default :
printf( “ Invalid arithmetic operator “ );
}
getch()
P2. Program to input month by number and after that print only how many days are available in that month.
#include<stdio.h>
#include<conio.h>
void mian()
{
clrscr();
int a;
printf( “ enter any month day no. “);
scanf( “ %d” , &a );
switch ( a )
{
case 1:
case 3 :
case 5 :
case 7 :
case 9 :
case 10 :
case 12 :
printf( “ 31 days “ );
break ;
case 2 :
printf( “ 28 or 29 days “);
break ;
case 4 :
case 6 :
case 9 :
case 11:
printf( “ 30 days “ );
break ;
default :
printf( “ Invalid months no. “ );
}
getch () ;
}
Program to find no. Of days of any month no. Entered |
No comments:
Post a Comment