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
C
#include <stdio.h>
int main() {
int id;
printf("Enter your ID: ");
scanf("%d", &id);
switch (id) {
case 100:
printf("Department: Computer Science\n");
break;
case 200:
printf("Department: Electronics\n");
break;
case 300:
printf("Department: Mechanical\n");
break;
default:
printf("Invalid ID\n");
break;
}
return 0;
}
Explanation:
- Header Inclusion:
#include <stdio.h>
provides input/output functions likeprintf
andscanf
. - Main Function: The program’s execution begins in the
main
function. - Variable Declaration:
int id;
declares an integer variable to store the user’s ID. - User Input:
printf
prompts the user to enter their ID, andscanf
reads the input and stores it in theid
variable. - Switch Statement:
- The
switch (id)
statement evaluates the value ofid
. - Each
case
label represents a potential value ofid
. - If
id
matches acase
label, the corresponding code block executes. - The
break
statement exits the switch statement after executing a case block. - The
default
case handles any value ofid
that doesn’t match the specified cases.
- The
- Department Output: The appropriate department is printed based on the matching
case
. - Invalid ID Handling: If
id
doesn’t match any case, thedefault
block prints “Invalid ID”. - 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.