Ā 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]