Lab 4
Lab 4
Lab Number: 4
Title: Control Flow with Switch Statements
Introduction
Control flow structures are essential for decision-making in programming. The switch statement
provides a structured and readable way to handle multiple conditions efficiently. This lab will
explore the syntax, usage, and practical applications of switch statements through examples and
hands-on tasks.
General Syntax:
switch(expression) {
case value1:
// Code to execute if expression matches value1
break;
case value2:
// Code to execute if expression matches value2
break;
...
default:
// Code to execute if none of the cases match
}
Key Points:
Example:
enum Days { MON, TUE, WED, THU, FRI };
Here, MON is assigned 0, TUE is 1, and so on. You can use enum in a switch statement for better
code organization:
Case 1
Case 2
In-Lab Tasks
1. Basic Calculator: Write a program that takes two integers and an operator (+, -, *, /) as
input and performs the corresponding operation using a switch statement.
2. Days of the Week: Implement a switch statement that takes an integer (1-7) as input
and prints the corresponding day of the week.
3. Vowel or Consonant: Write a program that takes a single letter as input and determines
if it is a vowel or consonant using a switch statement.
4. Menu-Driven Program: Create a simple menu system with 4 options and a default case
to handle invalid inputs.
Post-Lab Tasks
1. Number to Words: Modify Example 1 to handle numbers from 1 to 10 and print their
English word representation.
2. Convert Temperature Units: Write a program where the user inputs a temperature
value and a choice (C for Celsius to Fahrenheit, F for Fahrenheit to Celsius), and the
program performs the conversion using a switch statement.
3. Grade System Enhancement: Extend Example 2 to include more grades (D, F) and print
appropriate feedback messages.
Conclusion
This lab introduced switch statements, their syntax, and practical applications through
examples and exercises. Mastering switch statements allows for efficient multi-way decision-
making in programs, improving both readability and maintainability.