🔄

Understanding Switch Statements in C

Sep 10, 2024

C Programming Series: Switch Statement

Introduction

  • Instructor: Padma from Programmees
  • Topic: Switch statement in C programming
  • Objective: Learn to create decision-making programs using the switch statement
  • Example project: Calculator using switch statement

Scenario Overview

  • Given a number (1-7), print the day of the week:
    • Example: Number 1 = Sunday, Number 2 = Monday
  • Challenge with if-else statement:
    • Requires separate conditions for each number
    • Makes code messy and hard to understand

Switch Statement

Syntax

  • Starts with switch keyword
  • Followed by a variable or expression in parentheses
  • Contains multiple cases, each with its own value
  • Matching case's body is executed
  • If no match, default case body is executed

Example: Days of the Week Program

  • Declare variable: int number
  • Prompt user for input (number 1-7)
  • Use switch to print corresponding day:
    • Case 1: Sunday, Case 2: Monday, ..., Case 7: Saturday
  • Use default to handle invalid numbers
  • Use break to exit switch after executing a case

Demonstration

  • Input examples: 5 (outputs Thursday), 6 (outputs Friday), 9 (outputs Invalid number)
  • Importance of break statement:
    • Prevents fall-through execution of subsequent cases

Advanced Usage

  • Situations to omit break for multiple case execution:
    • Example: Check if a day is a weekday or weekend
    • Cases 2-6 print "Weekday"
    • Cases 1 & 7 print "Weekend"

Creating a Simple Calculator

  • Use switch statement for calculator functionality
  • Steps:
    • Declare operator variable
    • Ask user for operator input
    • Ask for two numbers
    • Store result of operation
    • Switch uses operator to perform the correct case operation

Examples

  • Addition: Operator +, numbers 8 & 12, result 20
  • Multiplication: Operator , numbers 9 & 5, result 45

Programming Task

  • Task: Use switch to find month from number input (1-12)
  • Example: 1 = January, 2 = February, ..., 12 = December
  • Solution available in GitHub repository

Conclusion and Quiz

  • Programming quiz provided at end of video
  • Engage with content: Comment, Like, Subscribe

Additional Resources

  • Mobile app for C programming course with certification
  • Free course with built-in compiler
  • GitHub repository link for code examples and tasks