Switch Statement in C Language

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.

if (salary=='10000')
cout<<"No Tax";
if (salary=='20000')
cout<<"10% Tax will be deduct";
if (salary=='30000')
cout<<"15% Tax will be deduct";
if (salary=='50000')
cout<<"20% Tax will be deduct";

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.

#include
main()
{
	char grade; 
	cout<<"Please enter your exam grade b/w (A-F): "; 	
        cin>>grade;
	switch(grade)
   {
   case 'A' :
   case 'a' :
      cout<<"Excellent Mark";
      break;
   case 'B' :
   case 'b' :
      cout<<"Great Effort";
      break;
   case 'C' :
   case 'c' :
      cout<<"Satisfactory Resultn";
      break;
   case 'F' :
   case 'f' :
      cout<<"You are fail. Try next timen";
      break;
   default :
      cout<<"Please enter valid grade b/w (A-F)n";
   }
}

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:

Switch Statement in C Language

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.

Leave a Reply

Your email address will not be published. Required fields are marked *