Switch Statement in C Language:
On some occasion, we use switch statement in C language. Let’s assume if We have various circumstance and decide to choose one of each then we use switch statement. Like in earlier article we talked about if else loop structure. We can suppose a tiny example, If 300 Peoples working in a company so in the end of month company able to pay all of these salaries but question is arising here, every person have different salary package and tax will be deduct in high salary persons. Tax deduct will apply on 20 thousand above salary employees and 50 thousand to next high salaries employee will also able to pay tax but with different ratio.
[crayon-58411ffa9d766806002417 inline="true" ]if (salary=='10000')
cout<<"10% Tax will be deduct";
cout<<"15% Tax will be deduct";
cout<<"20% Tax will be deduct";
[/crayon] Above example shows that, every employee of company have different ratio of tax. Same as here, we will reveal the format of switch statement below with grade activity program example.
[crayon-58411ffa9d76b015968833 inline="true" ]#include
cout<<"Please enter your exam grade b/w (A-F): ";
case 'A' :
case 'a' :
case 'B' :
case 'b' :
case 'C' :
case 'c' :
case 'F' :
case 'f' :
cout<<"You are fail. Try next timen";
cout<<"Please enter valid grade b/w (A-F)n";
[/crayon] Above code shows that, When program will compile then it run first condition then second and so on. Compiler check the first condition, if first condition meet our given query then compiler display cout of first condition and this procedure will run repeatedly till the end of all statement. Above program find out the grade activity for students. If you noticed that, we mentioned Break;with every switch case.Suppose your grade is “A” and after display “A” grade on-screen loop will not go ahead because this Break; interrupt the flow of loop and come outside the program.
Flow Chart of Switch Statement:
Now you can analyze the coding and flow chart both once. Try to utilize switch statement without if statement because if statement is an expensive statement in program and impact on your program. Don’t forget to put Break; after every switch case. In other condition, compiler will alert you with logical error. Always try to put default statement in the end of the program. You always should care about upper case letter or lower case letter in C language because both have different and action too. For more query and questions comment below.