C (programming language)

Switch-Case in C with Exercises and Solutions

The switch statement in C is a powerful tool for branching execution based on multiple conditions. It offers a more concise and readable alternative to nested if-else statements for handling scenarios with several distinct cases. This guide will delve into the intricacies of switch-case and provide several exercises with complete solutions to solidify your understanding.

Understanding the Syntax

The basic syntax of the switch statement is:

C

switch (expression) {
  case value1:
    // Code block 1
    break;
  case value2:
    // Code block 2
    break;
  ...
  default:
    // Code block for no match
    break;
  }
  1. Expression: This expression evaluates to a specific value or set of values. It can be an integer, character, or enumeration constant.
  2. Cases: Each case clause checks if the expression value matches the designated value. If a match is found, the corresponding code block within that case is executed.
  3. Break: Using break within a case block is crucial to prevent unwanted flow-through to subsequent cases.
  4. Default: The default clause handles situations where the expression value doesn’t match any of the specific cases. If omitted, the program skips the entire switch statement upon no match.

Advantages of Using Switch-Case

  • Improved Readability: Compared to nested if-else statements, switch-case makes code more structured and easier to understand, especially for handling multiple discrete conditions.
  • Reduced Errors: The strict case comparisons and optional break statements help minimize the risk of logic errors and unintentional flow-through.
  • Enhanced Efficiency: For specific types of comparisons, switch-case can be slightly more efficient than nested if-else due to its faster lookup mechanism.

Exercises and Solutions

Let’s tackle some exercises to solidify your grasp of switch-case:

Exercise 1: Day of the Week: Write a program that takes a number between 1 and 7 as input and prints the corresponding day of the week using switch-case.

Solution:

C

#include <stdio.h>

int main() {
  int dayNumber;

  printf("Enter a number between 1 and 7: ");
  scanf("%d", &dayNumber);

  switch (dayNumber) {
    case 1:
      printf("Monday\n");
      break;
    case 2:
      printf("Tuesday\n");
      break;
    case 3:
      printf("Wednesday\n");
      break;
    case 4:
      printf("Thursday\n");
      break;
    case 5:
      printf("Friday\n");
      break;
    case 6:
      printf("Saturday\n");
      break;
    case 7:
      printf("Sunday\n");
      break;
    default:
      printf("Invalid Day Number\n");
      break;
  }

  return 0;
}

Exercise 2: Grade Checker: Design a program that accepts a letter grade (‘A’, ‘B’, ‘C’, ‘D’, or ‘F’) and prints a corresponding message using switch-case.

Solution:

C

#include <stdio.h>

int main() {
  char grade;

  printf("Enter your grade (A, B, C, D, or F): ");
  scanf("%c", &grade);

  switch (grade) {
    case 'A':
      printf("Excellent!\n");
      break;
    case 'B':
      printf("Good job!\n");
      break;
    case 'C':
      printf("Average performance.\n");
      break;
    case 'D':
      printf("Work harder next time.\n");
      break;
    case 'F':
      printf("You need to improve significantly.\n");
      break;
    default:
      printf("Invalid grade entered.\n");
      break;
  }

  return 0;
}


Exercise 3: Menu System

C

#include <stdio.h>

int main() {
  int choice;

  printf("Menu:\n");
  printf("1. Calculate Area\n");
  printf("2. Display Information\n");
  printf("3. Exit\n");

  printf("Enter your choice: ");
  scanf("%d", &choice);

  switch (choice) {
    case 1:
      // Implement code to calculate area based on user input (e.g., shapes)
      break;
    case 2:
      // Print program information or specific details
      break;
    case 3:
      printf("Exiting program...\n");
      return 0; // Exits the program
    default:
      printf("Invalid choice. Please enter a number between 1 and 3.\n");
      break;
  }

  return 0; // Program continues if not exiting in case 1 or 2
}

This example demonstrates how to utilize switch-case to build a branching menu system, allowing users to select specific functionalities within your program. You can expand this further by adding more menu options and implementing the corresponding code inside each case block.

Remember, these exercises are just a starting point. As you gain more experience, you can tackle more complex scenarios with switch-case and improve your ability to write clear and efficient C code.

I hope this complete guide with exercises and solutions helps you master the power and versatility of switch-case in C!

CodeForHunger

Learn coding the easy way. Find programming guides, examples and solutions with explanations.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button