×

C Switch Statements

Switch-case statement comes under the Selection control statement; there are four types of Control statements

  1. Decision-making statements (if, if-else)
  2. Selection statements (Switch-case)
  3. Iteration statements (for, while, do-while)
  4. Jump statements (break, continue, goto)

If we want to write a program with one condition, then we use if-else statements. And if we want to write a program containing many conditions, then we will use an if-else ladder that supports many conditions simultaneously.

Instead of using the if-else ladder, we use the switch statement. In the switch statement, we build many blocks known as cases, and there must be a default case at the end of every switch statement.

  • In the switch statement, we pass a value that will check all the case’s values. If that value matches the case value, then that case will be executed. Otherwise, the default case will be executed.
  • In the if-else ladder, the conditions are evaluated continuously. But in the switch statement, the expression is evaluated only once.

When the expression value is matched with the case value, then that case statement will be executed until it reaches the break statement in the particular block.

  • After every case, we use a break statement to come out of the switch block and stop the execution. The program will not stop execution if we forget to use a break statement in our program.
  • If there is no case value matching the expression value, then the default statement will be executed. We will not give a break statement in the default case.
  • In the switch statement, all the cases are numbered like case 1, case 2, case 3,………, and case n.

Syntax for switch statement:

Switch ( expression )
{
Case 1: {
		Statement (s);
		break;
	         }
Case 2: {
		Statement (s);
		break;
	        }


Case 3: {
		Statement (s);
		break;
	       }
//we can have any number of case statements in the program
Default: {
		Statement (s);
	         }
}

Example 1:

//simple program for switch-case statement
#include <stdio.h>            //pre-processor standard input and output
#include <conio.h>	//pre-processor clear screen before scanning the value
Int main ()
{
int num;	//declaring integer variable
clrscr();	//clear screen command
printf(“enter the value of num:”);
scanf(“%d”, &num);	//scanning the variable data


Switch(num)	//passing the scanned value in the switch statement
{
Case 1:	//declaring case 1 with executable statements
	printf(“Hi all this is case-1”);
	Break;
Case 2:	//declaring case 2 with executable statements
	printf(“Hello, this is case-2”);
	Break;
Case 3:	//declaring case 3 with executable statements
	printf(“Hello, this is case-3”);
	Break;
Case 4:	//declaring case 4 with executable statements
	printf(“Hello, this is case-4”);
	Break;
Default:	//declaring default case with print statements
	printf(“Invalid choice”);
}
return 0;
}

Output:

Test case 1:

Enter the value of num: 4
Hello, this is case 4.

Explanation:

In the above test case, we have given the number 4, and in the program, we have given case 4 both the numbers are matched. So, case 4 will be executed.

 Test case 2:

Enter the value of num: 8
Invalid choice

Explanation:

In the above test case, we have given the number 8, and in the program, we have not declared any case 8. Here expression value and case value are not matched. So, the default case will be executed.

Example 2:

//program for switch-case statements
#include <stdio.h>            //pre-processor standard input and output
#include <conio.h>	//pre-processor clear screen before scanning the value
Int main ()
{
int n;	//declaring integer variable
clrscr();	//clear screen command
printf(“enter the value of n:”);
scanf(“%d”, &n);	//scanning the variable data


Switch(n)	//passing the scanned value in the switch statement
{
Case 10:	//declaring case 1 with executable statements
{
      Int a;	//declaring integer variable a
      Printf(“enter the a value:”);
      Scanf(“%d”, &a);              //scanning the variable data(a)
      printf(“The division of two numbers is %d”,(n/a));           //printing the result
	Break;
}
Case 20:	//declaring case 2 with executable statements
{	
       Int b;                       //declaring integer variable b
	Printf(“enter the b value:”);
      Scanf(“%d”, &b);                 //scanning the variable data(b)
      printf(“The multiplication of two numbers is %d”,(n*b));    //printing the result
	Break;
}
Case 30:	//declaring case 3 with executable statements
{
	Int a;                    //declaring integer variable a
	Printf(“enter the a value:”);
      Scanf(“%d”, &a);      //scanning the variable data(a)
printf(“The addition of two numbers is %d”,(a+n));           //printing the result
	Break;
}
Case 40:	//declaring case 4 with executable statements
{
	Int b;                                //declaring integer variable b
	Printf(“enter the b value:”);
       Scanf(“%d”, &b);       //scanning the variable data(b)
printf(“The subtraction of two numbers is %d”, (n-b));        //printing the result
	Break;
Default:	//declaring default case with print statements
	printf(“Invalid choice”);
}
return 0;
}

Output:

Test case 1:

Enter the value of n: 40
Enter the b value: 25
The subtraction of two numbers is 15.

Explanation:

We have given the expression value 40, so in the program, there is a case value 40. Both are the same, so case 40 will be executed. And the output will be (40-25) = 15.

Test case 2:

Enter the value of n: 20
Enter the b value: 5
The multiplication of two numbers is 100.

Explanation:

We have given the expression value 20, so the program has a case value matching the expression value. Both are the same, so case 20 will be executed. And the output will be (20*5) = 100.

Test case 3:

Enter the value of n: 10
Enter the a value: 2
The division of the two numbers is 5.

Explanation:

We have given the expression value 10, so the program has a case value matching the expression value. Both are the same, so case 10 will be executed. And the output will be (10/2) = 5.

Test case 4:

Enter the value of n: 30
Enter the a value: 10
The addition of the two numbers is 40.

Explanation:

We have given the expression value 30, so the program has a case value matching the expression value. Both are the same, so case 30 will be executed. And the output will be (30+10) = 40.

Test case 5:

Enter the value of n: 70
Invalid choice.

Explanation:

We gave the expression value 70, so the program doesn’t have a case value matching the expression value. So the out will be “Invalid choice”.


Related Topics

C Programming Tutorial

What is C Programming C is most popular and widely used computer programming language. It was developed by Dennis Ritchie in 1972 at the Bell Lab. It is used to develop system application software. There...

8 minutes read.

#error #pragma in C

#error, #pragma in C #error, also known as the error directive in the C language. It will not allow you to make any compilation fail and immediately issues a statement which...

4 minutes read.

Factorial Program in C Using While Loop

Before looking into the mechanism of factorial program, first, you have to understand about the working of a while loop. While Loop The syntax that has been used for the “while” loop...

4 minutes read.

Multi-dimensional Arrays in C

Multi-dimensional Arrays in C The C programming allows the concept of multi-dimensional arrays. The data within the multidimensional arrays are stored in the tabular form, that is, in a row significant...

3 minutes read.

2f in C language

Float data type in c: Double-precision floating-point numbers with up to 17 significant digits are stored in the FLOAT data type. FLOAT is equivalent to C's double data type and IEEE...

3 minutes read.

Use of Structure in C

We can usually use arrays in C programming to store elements of the same data type. We can use strings to store multiple elements of a character data type. Still,...

4 minutes read.

Formatted Input and output function in C

Formatted I/O functions display multiple outputs to the user by taking various inputs. All data types like int, float, char and double are supported by the formatted I/O function. In...

4 minutes read.

Keywords in C

A keyword is a word that has a predetermined meaning. The C compiler knows the purposes of the keywords. The objectives of these keywords cannot be modified. Keywords are the...

9 minutes read.

GCD program in C

C language : Dennis Ritchie developed the general-purpose computer language C at Bell Laboratories in 1972. Despite being an ancient language, it is extremely popular. It is among the most widely used...

4 minutes read.

Difference between C and Java

C programming and Java programming are two of the earliest programming languages. C programming follows a procedural approach whereas Java programming follows an object-oriented approach. Java programming is a part...

3 minutes read.

Difference between If and Switch Statement in C

Key Contrast: In the event that assertion is utilizes a Boolean articulation to execute the capability and can frequently be utilized to really look at various circumstances all at once.  The change...

4 minutes read.

Errors in C

Errors in C Errors are nothing but problems or faults that pretty much occur in all the programming languages. Errors make the behavior of the program seem abnormal, and even the...

4 minutes read.

Self-referential structure in C

Self-referential structure in C A self-referential structure is a structure that can have members which point to a structure variable of the same type. They can have one or more pointers...

3 minutes read.

Integer Promotions in C

As we know that some of the data types such as char, short int, Enum takes a smaller number of bytes than compared to int. When an operation is applied...

3 minutes read.

How to use Typedef Struct in C

The “typedef” is a predefined keyword in C programming language which is used to declare the new name to an existing type of variable. For better understanding, if you declare a...

3 minutes read.

Structure in C

Why Structure came into the picture? In the actual world, we deal with entities that are collections of objects rather than tiny bits of data like integers, characters, floats, etc. So,...

4 minutes read.

File Handling in C

File Handling is used to open, read, write, search and close file.  C files I/O functions handles data on secondary storage device. File handling function: There are varioushandling functions in C. Function Operation fopen() It is...

4 minutes read.

Const vs Volatile in C

Introduction Qualifiers are nothing but keywords which are used to modify the properties of a variable. Const and Volatile keywords are qualifiers in C. The Const qualifier is applied to the...

4 minutes read.

Pre-increment and Post-increment in C

The rich set of operators is supported by the c language. In c there are several operators used. The mathematical operations in the programming language are done with the operators...

4 minutes read.

Decimal to Hexadecimal in C

Decimal to Hexadecimal in C Let us first understand the definitions of decimal and hexadecimal. In algebra, a decimal number is defined as a number whose whole number part and a...

3 minutes read.