C Programming: Nested Switch Statement 🎯

beginner
15 min

C Programming: Nested Switch Statement 🎯

Welcome to the tutorial on the Nested Switch Statement in C programming! We'll learn how to use it, why it's useful, and see some practical examples. Let's dive in!

What is a Switch Statement? 📝

The switch statement is used to compare the value of a variable or expression with multiple constants or cases. When a match is found, the code block associated with that case is executed.

Nested Switch Statement 💡

A nested switch statement refers to a switch statement within another switch statement. It allows you to create more complex decision structures, where each case can contain another switch.

Why Use a Nested Switch? 📝

Nested switches are useful when dealing with complex decision-making scenarios that involve multiple levels of choices. For example, consider a system that classifies students based on their marks in multiple subjects. In this case, a nested switch can help simplify the decision-making process.

Syntax 📝

c
switch (expression) { case constant1: // Code block for constant1 break; case constant2: // Code block for constant2 break; ... default: // Default code block }

Nested Switch Example 💡

Let's create a simple example of a nested switch to demonstrate its usage. We'll create a system that converts temperature from Fahrenheit to Celsius and vice versa.

c
#include <stdio.h> void convertFtoC(int fahrenheit) { float celsius = (fahrenheit - 32.0) * 5.0 / 9.0; printf("Temperature in Celsius: %.2f\n", celsius); } void convertCtoF(float celsius) { float fahrenheit = celsius * 9.0 / 5.0 + 32.0; printf("Temperature in Fahrenheit: %.2f\n", fahrenheit); } int main() { char unit; float celsius, fahrenheit; printf("Enter temperature unit (F/C): "); scanf(" %c", &unit); if (unit == 'F') { printf("Enter temperature in Fahrenheit: "); scanf("%f", &fahrenheit); convertFtoC(fahrenheit); } else if (unit == 'C') { printf("Enter temperature in Celsius: "); scanf("%f", &celsius); convertCtoF(celsius); } else { printf("Invalid temperature unit. Please enter F or C.\n"); } return 0; }

In this example, we have two functions for converting Fahrenheit to Celsius and vice versa. In the main() function, we first get the temperature unit (Fahrenheit or Celsius) from the user. Then, we use a nested switch to handle the conversion based on the entered unit.

Nested Switch with Multiple Levels 💡

For multiple levels of nested switches, the outer switch is executed first, followed by the inner switch associated with the matched case of the outer switch. This process continues until all nested switches are executed.

Quiz 🎯

Quick Quiz
Question 1 of 1

What is a nested switch statement in C programming?