Pages

Friday, July 31, 2020

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");

printf("Enter your choice (1-4);
scanf("%d",&c)

switch(c)
{
case 1:
r=a+b; break;

case 2:
r=a-b; break;

case 3:
r=a*b; break;

case 4:
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':
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

No comments:

Post a Comment