Switch…case: C Program

0
1636
Ā 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.

switch case[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();
}

[/message_box] [message_box title=”Output” color=”red”]

Enter day Number:3

Tuesday is the third day of the week

[/message_box]
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments