Switch Case in C Language

switch case in c

We studied earlier in decision control that how and when to use if, if-else. They are good enough to select one from the two available options. When choices are two, we can use if-else. Even if we have multiple choices we can use multiple if-else, sometimes we use if-else ladder or nested if-else becomes more complex. Whenever we have many choices(cases) and we have to choose one of them(generally), it is better to use switch case control.

In this section we are going to learn three keywords, case and default. Apart from these keywords we will also see usage of break keyword in switch body.

Syntax 


switch case in c,switch statement in c
switch case in c
Switch statement is used to solve multiple option type problems for menu like program, where one value is associated with each option. The expression in switch case evaluates to return an integral value, which is then compared to the values in different cases, where it matches that block of code is executed, if there is no match, then default block is executed. Switch case control is very useful in menu driven program. The following example illustrates menu driven program. It is also use break to terminate switch.

Example


int main()
{
int a, b, result, ch;
while(1) // 1 means condition is always true, thus an infinite loop.
{
printf("\n1. Addition");
printf("\n2. subtraction");
printf("\n3. multiplication");
printf("\n4. division");
printf("\n5. exit");
printf("\n\n. enter your choice");
scanf("%d", &ch);
switch(ch)
{
case 1:
printf("enter two numbers");
scanf("%d%d", &a,&b);
result=a+b;
printf("sum is %d", result);
break; 
case 2:
printf("enter two numbers");
scanf("%d%d", &a,&b);
result=a-b;
printf("difference is %d", result);
break; 
case 3:
printf("enter two numbers");
scanf("%d%d", &a,&b);
result=a*b;
printf("product is %d", result);
break; 
case 4:
printf("enter two numbers");
scanf("%d%d", &a,&b);
result=a/b;
printf(" quotient is %d", result);
break; 
case 5:
exit(0);
default:
printf("invalid entry");
}
getch();
}
return(0);
}

Explanation:

There are few things to discuss about above program.

Notice while loop which executes infinite times till you select 5 from the menu. In case 5, we use a predefined function exit. The job of this function is to terminate program. Argument 0 in the function depicts the normal termination. Argument could be 1 passed in the function in the case of abnormal termination. The break keyword is used in each case as it transfers the control outside switch body. Whenever wrong selection from menu (other than value from 1 to 5) switch moves the control to default segment. No need to put keyword break after default statements as it is already at the end of switch body. Rest you can understand the flow of program by executing it.

Comments

Popular posts from this blog

Notepad, Wordpad and Paint

HOW TO PASS CCC EXAM WITH ONE ATTEMPT (NIELIT)

Inheritance in C++ Language(part 1)