The switch
statement in C (and other programming languages) is a control structure that allows you to execute different parts of code based on the value of a variable or expression. It can be a cleaner alternative to using multiple if-else
statements when dealing with numerous possible values.
Syntax
Here’s the basic syntax of a switch
statement:
switch (expression) {
case value1:
// Code to execute if expression == value1
break;
case value2:
// Code to execute if expression == value2
break;
// …
default:
// Code to execute if expression doesn’t match any case
}
Key Components
- Expression: The variable or expression being evaluated. It must evaluate to an integral type (like
int
orchar
). - Case Labels: Each
case
specifies a constant value to compare against the expression. If there’s a match, the code following thecase
will execute. - Break Statement: This statement exits the
switch
block. Without abreak
, execution will continue to the next case (fall-through behavior). - Default Case: This is optional and executes if none of the
case
labels match the expression.
Example
Here’s a simple example of a switch
statement in C:
#include <stdio.h>
int main() {
int day = 3;
switch (day) {
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\n”);
}
return 0;
}
C Program to Calculate Simple and Compound Interest
#include <stdio.h>
#include <math.h>
int main() {
int choice;
float principal, rate, time, simpleInterest, compoundInterest, amount;
printf(“Choose the type of interest to calculate:\n”);
printf(“1. Simple Interest\n”);
printf(“2. Compound Interest\n”);
printf(“Enter your choice (1 or 2): “);
scanf(“%d”, &choice);
switch (choice) {
case 1: // Simple Interest
printf(“Enter principal amount: “);
scanf(“%f”, &principal);
printf(“Enter rate of interest (in %%): “);
scanf(“%f”, &rate);
printf(“Enter time (in years): “);
scanf(“%f”, &time);
simpleInterest = (principal * rate * time) / 100;
printf(“Simple Interest: %.2f\n”, simpleInterest);
break;
case 2: // Compound Interest
printf(“Enter principal amount: “);
scanf(“%f”, &principal);
printf(“Enter rate of interest (in %%): “);
scanf(“%f”, &rate);
printf(“Enter time (in years): “);
scanf(“%f”, &time);
printf(“Enter number of times interest applied per time period: “);
int n;
scanf(“%d”, &n);
amount = principal * pow((1 + rate / (n * 100)), n * time);
compoundInterest = amount – principal;
printf(“Compound Interest: %.2f\n”, compoundInterest);
break;
default:
printf(“Invalid choice. Please choose 1 or 2.\n”);
break;
}
return 0;
}