C (programming language)

C program to accept id from user to confirm department using switch-case

Understanding the Problem

  • The program aims to collect an ID from the user and identify their corresponding department using a switch-case structure.
  • This structure offers a clear and efficient way to handle multiple conditional branches based on a single variable’s value.

Code Structure and Explanation


#include <stdio.h>

int main() {
    int id;

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

    switch (id) {
        case 100:
            printf("Department: Computer Science\n");
        case 200:
            printf("Department: Electronics\n");
        case 300:
            printf("Department: Mechanical\n");
            printf("Invalid ID\n");

    return 0;


  1. Header Inclusion: #include <stdio.h> provides input/output functions like printf and scanf.
  2. Main Function: The program’s execution begins in the main function.
  3. Variable Declaration: int id; declares an integer variable to store the user’s ID.
  4. User Input: printf prompts the user to enter their ID, and scanf reads the input and stores it in the id variable.
  5. Switch Statement:
    • The switch (id) statement evaluates the value of id.
    • Each case label represents a potential value of id.
    • If id matches a case label, the corresponding code block executes.
    • The break statement exits the switch statement after executing a case block.
    • The default case handles any value of id that doesn’t match the specified cases.
  6. Department Output: The appropriate department is printed based on the matching case.
  7. Invalid ID Handling: If id doesn’t match any case, the default block prints “Invalid ID”.
  8. Return Statement: return 0; indicates successful program termination.

Key Points:

  • The switch-case structure provides a clean and efficient way to handle multiple conditional branches based on a single variable’s value.
  • It’s often preferred over multiple if-else if statements when dealing with several possible values for a variable.
  • Ensure each case block has a break statement to prevent unintended execution of subsequent cases.
  • The default case is optional but serves as a catch-all for unexpected values.
  • Consider using a while loop to allow for repeated ID entry and department confirmation if needed.


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