C Programming

place your ad here

The Switch Statement || Control Statements || CSIT Notes

The Switch Statement

The Switch Statement

The Switch Statement is a multi-directional condition control statements. Sometimes there is a need in the program to make choices among a number of alternatives. For making this choice, we use the switch statements.

The same task can be performed using an if-else ladder as well but as the number of alternatives increases, the selection process becomes more complex (more time consuming). The main difference between the if-else ladder and switch statement is: In if-else ladder selection of appropriate option is made in serial fashion whereas in a switch-case it is done in a parallel fashion. So the switch statement is much faster than the if-else ladder. The switch statement body consists of a series of case labels and an optional default label. The default label can appear only once and anywhere in the body of the switch statement.

Syntax

switch (expression)
{
case constant1:
statement 1;
break;
case constant2:
statement 2;
break;
case constant3:
statement 3;
break;
default:
statement;
}

Flowchart

Examples

Write a program to print the day of the week according to the number entered 1 for Sunday ……..7 for Saturday.
#include<stdio.h>
#include<conio.h>
void main()
{
int num;
clrscr();
printf(“Enter a number\n”);
scanf(“%d”,&num);
switch(num)
{
case 1:
printf(“Sunday”);
break;
case 2:
printf(“Monday”);
break;
case 3:
printf(“Tuesday”);
break;
case 4:
printf(“Wednesday”);
break;
case 5:
printf(“Thusday”);
break;
case 6:
printf(“Friday”);
break;
case 7:
printf(“Saturday”);
break;
default:
printf(“Wrong input”);
}
getch();
}

Output:

Write a program to perform arithmetic calculation based on the operators entered by user.
+ for addition, – for subtraction, * for multiplication, / for division and % for remainder.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
char op;
clrscr();
printf(“Enter operator\n”);
scanf(“%c”,&op);
printf(“Enter two numbers\n”);
scanf(“%d%d”,&a,&b);
switch(op)
{
case ‘+’:
printf(“Sum =%d”,a+b);
break;
case ‘-‘:
printf(“Difference =%d”,a-b);
break;
case ‘*’:
printf(“Product =%d”,a*b);
break;
case ‘/’:
printf(“Quotient =%d”,a/b);
break;
case ‘%’:
printf(“Remainder =%d”,a%b);
break;
default:
printf(“Wrong operator”);
}
getch();
}

Output:

If you liked our content The Switch Statement, then do not forget to check our other topics The Goto Statement

Please don’t forget to connect with us through our social media sites, Facebook: Online Notes Nepal, Instagram: @online_notes_nepal, LinkedIn: @onlinenotesnepal, and Twitter: @onlinenotenepal.

advertise here
webtrickshome