C Tutorial — Learn C Programming
Key takeaway: This free C tutorial teaches you systems programming from scratch — variables, pointers, arrays, functions, structs, and memory management — with practical code examples you can compile and run.
C is a general-purpose, procedural programming language created in 1972. It is used for operating systems, embedded systems, game engines, and performance-critical applications. This tutorial is for beginners, CS students, and developers who want to understand how computers work at a low level.
Last updated: September 2026
switch Statement in C
The switch statement provides an efficient way to execute different blocks of code based on the value of a variable. It's an alternative to multiple if...else if statements.
Basic switch Statement
#include <stdio.h>
int main() {
char operator;
double num1, num2, result;
printf("Enter an operator (+, -, *, /): ");
scanf("%c", &operator);
printf("Enter two numbers: ");
scanf("%lf %lf", &num1, &num2);
switch (operator) {
case '+':
result = num1 + num2;
printf("%.2lf + %.2lf = %.2lf\n", num1, num2, result);
break;
case '-':
result = num1 - num2;
printf("%.2lf - %.2lf = %.2lf\n", num1, num2, result);
break;
case '*':
result = num1 * num2;
printf("%.2lf * %.2lf = %.2lf\n", num1, num2, result);
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
printf("%.2lf / %.2lf = %.2lf\n", num1, num2, result);
} else {
printf("Error: Division by zero!\n");
}
break;
default:
printf("Error: Invalid operator!\n");
}
return 0;
}switch vs if...else
switch Statement
- More efficient for multiple conditions
- Only works with integer and character values
- Uses exact value matching
- Requires break statements
if...else Statement
- Works with any data type
- Supports complex conditions
- Can use logical operators
- More flexible for ranges
Important Notes
- Always use
breakstatements to prevent fall-through - The
defaultcase is optional but recommended - switch works only with integer and character constants
Explanation
- switch: Compares a single expression against constant cases; great for menus, commands, and exact matches.
- break: Prevents execution from falling through to the next case; include it in each handled case.
- default: Catches unmatched values; use to provide helpful feedback or safe behavior.
- When to use: Prefer
switchfor discrete values; useif...elsefor range checks or complex conditions.
Keywords
Quick Tips
- Group related cases intentionally with fall-through, but document it clearly.
- Validate input before the
switchto avoid handling invalid states. - Keep case bodies small; move logic into functions for readability.