In the previous lesson, we learned about the flow control structure. We learned about the if-else structures and nested if structures. In this lesson, we will learn about another flow control feature – switch-case.
Consider a C program for calculator, the user is given a menu with options to choose from.
We can write a program using if-else construct for the above problem.
The user enter a number and it is matched with if-else blocks and whenever there is a match that block is executed.
The problem with these kind of construct is that when the menu if large, then the if-else construct will be difficult to manage. Also, there are many comparisons – each if block is tested.
The switch-case is suitable for menu driven C programs. Whenever the program is executed, a menu with number of choices like the example below is presented to the user.
/* Calculator Application in C */
Enter your choice:
The switch block look like the following in program source code. The switch block accepts a number as user choice.
When the user enters a number next to an option and the Switch accepts the choice(number).
The switch () matches the user choice with a list of cases. Each of the cases have number associated with them followed by a colon.
When the user choice and the case number matches, the statements from the case is executed and terminated by a break; statement.
The entire switch-case block look like following
Let’s create an example program using the Switch-Case. We shall write the Calculator program using the Switch-Case.
Flowchart – C Calculator
int a, b, c;
a = 10;
b = 20;
printf (“Enter your choice :”);
scanf (“%d”, &choice);
c = a + b;
c = a - b;
c = a * b;
c = a / b;
printf (“Wrong choice, try again!”);
printf (“Result = %d\n”, c);
The output of the program is given below.
Balagurusamy, E. 2000. Programming in ANSI C. Tata McGraw-Hill Education,.
Kanetkar, Yashavant. 20 November 2002. Let us C. Bpb Publications.