×

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

Compound Interest Program in C

Interest on loans and deposits is compound interest. This is the most commonly used concept in everyday life. Compound interest on an amount is based on principal and interest earned...

3 minutes read.

C program to Store Information of Students Using Structure

What is the Structure in C? User-defined data types include structures. Structures aid your ability to combine things of various categories into a single group. Like arrays, it operates similarly. A...

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.

Ferror() in c

Ferror():  In C, the ferror() function checks assuming there is a blunder in the given stream. The ferror() function is utilized to check for the document blunder on given stream. A return...

4 minutes read.

Malloc function in C

When the user or programmer does not know how much memory space is needed in the application, it a needs dynamic memory allocation during runtime. Dynamic memory allocation helps us to...

4 minutes read.

Exponential() in C

Introduction: In C language, there are available many types of functions. The exponential() function is one of them. It is a mathematical function. This article describes using the pow() property to...

3 minutes read.

Multithreading in C interview questions

Q1. What exactly is a thread? Ans: A thread is a brief sequence of instructions intended to be planned and carried out by the CPU apart from the parent process. Q2. Can...

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.

Stack implementation in C

Stack implementation in C Stack stores the data in a particular order. It is a linear data structure that follows the principle of the Last In First Out (LIFO) technique where...

3 minutes read.

Quick sort in C

Quick-sort, in the same way, like a merge sort, follows the principle of the divide and conquer algorithm. It then picks an element as pivot and partitions, and the given...

4 minutes read.

Stdio.h in C

Header files are used to make the programmer’s efforts a lot easier. In order to make the programming simple, there are a number of libraries which are included as predefined...

4 minutes read.

Armstrong Number in C

The Armstrong number is defined as the sum of each of its digits to the power of the number base for the each given number with any given number base....

3 minutes read.

C Program to find the Roots of a Quadratic Equation

What is Quadratic Equation: Equations of degree 2 in polynomial form are called quadratic equations. A, B, and C are the coefficient variables in the equation, which is written as ax2...

3 minutes read.

C Decision control statement

Decision Making C conditional statements are used to specify one or more conditions. The statements will be executed if the condition becomes true otherwise alternative statement will be executed if the...

3 minutes read.

Float in islower() in C

Introduction: This article briefly discusses the float in islower() in C. The islower() function checks if the input character passed inside the function is lowercase. Lowercase letters include (a-z). The islower()...

4 minutes read.

Flow chart of While loop in C

This is a flowchart that represents the process of executing the while loop in the C programming language.Generally, as we know there are three main components of while loop:1. The...

3 minutes read.

C program that does not Suspend when Ctrl+Z is Pressed

In Programming when a program breakdown and runs surprisingly in the terminal compiler the developer has the ability to prevent the program from running unequivocally. For expressly halting the program,...

3 minutes read.

How to convert a string to hexadecimal in C

Converting a character array or any string to its respective hexadecimal form is simple. The only thing we have to do is to follow the below steps. Take each character from...

3 minutes read.

C Program for Extended Euclidean algorithms

The Euclidean method simply computes the GCD (greatest common divisor) of two numbers, p and q. (Let's assume) The GCD of two integers is the greatest number that divides them both....

3 minutes read.

Enumeration (Enum) in C

Enumeration (Enum) in C: In the C programming language, the enum is referred to as an enumerated type. Enum is a user defined data type consisting of integer values and...

3 minutes read.