Thursday 5 March 2015

The switch Construct in C

Instead of using if-else-if ladder, the switch construct can be used to handle multiple choices, such as menu options. The syntax of the switch construct is different from if-else construct. The objective is to check several possible constant values for an expression. It has the form:

switch (control variable)
{
case constant-1:
statement(s);
break;
case constant-2:
statement(s);
break;
case constant-n:
statement(s);
break;
default:
statement(s);
}

The switch construct starts with the switch keyword followed by a block which contains the different cases. Switch evaluates the control variable and first checks if its value is equal to constant-1; if it is the case, then it executes the statement(s) following that line until it reaches the break keyword. When the break keyword is found no more cases will be considered and the control is transferred out of the switch structure to next part of the program. If the value of the expression is not equal to constant-1 it will check the value of constant-2. 

If they are equal it will execute relevant statement(s). This process continuous until it finds a matching value. If a matching value is not found among any cases, the statement(s) given after the default keyword will be executed. The control variable of the switch must be of the type int, long or char (any other datatype is not
allowed). Also note that the value we specify after case keyword must be a constant and cannot be a variable (example: n*2).

menu item. Based on the user’s selection display the category of software that the user selected program belongs to.

Menu
-----------------------------------
1 – Microsoft Word
2 – Yahoo messenger
3 – AutoCAD
4 – Java Games
-----------------------------------
Enter number of your preference:

Program-4.9 implements a solution to the above problem:

/* Program-4.9 */

#include <stdio.h>
int main()
{
int a;
printf("\t\tMenu");
printf("\n-----------------------------------");
printf("\n1 - Microsoft Word");
printf("\n2 - Yahoo messenger");
printf("\n3 - AutoCAD");
printf("\n4 - Java Games");
printf("\n-----------------------------------");
printf("\nEnter number of your preference: ");
scanf("%d",&a); //read input
switch (a)
{
case 1: //if input is 1
printf("\nPersonal Computer Software");
break;
case 2: //if input is 2
printf("\nWeb based Software");
break;
case 3: //if input is 3
printf("\nScientific Software");
break;
case 4: //if input is 4
printf("\nEmbedded Software");

break;
default:
printf("\nIncorrect input");
}
return 0;
}
Executing Program-4.9 will display the following:
Menu
-----------------------------------
1 - Microsoft Word
2 - Yahoo messenger
3 - AutoCAD
4 - Java Games
-----------------------------------
Enter number of your preference: 1
Personal Computer Software

No comments:

Post a Comment