This program is about Switch…case statement.
Decision making are needed when, the program encounters the situation to choose a particular statement among many statements. If a programmer has to choose one block of statement among many alternatives, nested if…else can be used but, this makes programming logic complex. This type of problem can be handled in C programming using switch
statement.
[message_box title=”Syntax of switch…case” color=”red”]
switch (n) { case constant1: code/s to be executed if n equals to constant1; break; case constant2: code/s to be executed if n equals to constant2; break; . . . default: code/s to be executed if n doesn't match to any cases; } [/message_box]
The value of n is either an integer or a character in above syntax. If the value of n matches constant in case
, the relevant codes are executed and control moves out of the switch
statement. If the n doesn’t matches any of the constant in case, then the default codes are executed and control moves out of switch
statement.
[message_box title=”Program” color=”red”]
/* Write a program that reads a number from 1 to 7 and accordingly it
should display Sunday to Saturday */
/* Written by Utpal Chaudhary */
#include<stdio.h>
#include<conio.h>
void main()
{
int day;
clrscr();
printf(“Enter day number : “);
scanf(“%d”,&day);
switch(day)
{
case 1:
printf(“Sunday is the first day of the week”);
break;
case 2:
printf(“Monday is the second day of the week”);
break;
case 3:
printf(“Tuesday is the third day of the week”);
break;
case 4:
printf(“Wednesday is the fourth day of the week”);
break;
case 5:
printf(“Thursday is the fifthe day of the week”);
break;
case 6:
printf(“Friday is the sixth day of the week”);
break;
case 7:
printf(“Saturday is the seventh day of the week”);
break;
default:
printf(“You have entered a wrong choice”);
}
getch();
}
Enter day Number:3
Tuesday is the third day of the week
[/message_box]