SWITCH STATEMENT IN C
Like Else if statement the switch statement is also used to implement two and more than two logical conditions.Example 1: Program to perform mathematical calculation according to user choice.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int a,b,c,r;
printf("Enter first number:");
scanf("%d",&a);
printf("Enter second number:");
scanf("%d",&b);
printf("1. Add \t 2. Sub\n");
printf("3. Mul \t 4. Div");
scanf("%d",&c)
switch(c)
{
case 1:
r=a+b; break;
case 2:
r=a-b; break;
case 3:
r=a*b; break;
r=a*b; break;
case 4:
r=a/b; break;
r=a/b; break;
}
printf("Result is: %d",r);
getch();
}
- - - OUTPUT - - -
Enter first number: 6
Enter second number: 2
Result is: 4
Example 2: Program to count total number of vowels in a string entered by user at run time.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
clrscr();
char s[60];
int L,V=0;
int i;
printf("Enter any sentence:\n");
gets(s);
L=strlen(s);
for(i=0; i<L; i++)
{
switch(s[i])
{
case 'a': case'A':
case 'e': case'E':
}
printf("Total number of vowels: %d",V);
getch();
}
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
clrscr();
char s[60];
int L,V=0;
int i;
printf("Enter any sentence:\n");
gets(s);
L=strlen(s);
for(i=0; i<L; i++)
{
switch(s[i])
{
case 'a': case'A':
case 'e': case'E':
case 'i': case'I':
case 'o': case'O':
case 'u': case'U':
V=V+1;
}}
printf("Total number of vowels: %d",V);
getch();
}
- - - OUTPUT - - -
Enter any sentence:
Welcome in Enotes4
Total number of vowels: 6
Example 3: Program to generate shopping bill.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
clrscr();
int c,q,b;
printf("1. Tea Rs. 10 \t 2. Coffee Rs. 25");
printf("\n3. Cold drink Rs. 40 \t 4. Samosa Rs. 12");
printf("Enter your choice:");
scanf("%d",&c);
printf("Enter quantity:");
scanf("%d",&q);
switch(c)
{
case 1:
b=q*10; break;
case 2:
b=q*25; break;
case 3:
b=q*40; break;
case 4:
b=q*12; break;
}
printf("Total bill amount is: %d",b);
getch();
}
0 Comments