- The Case Control Structure:
The case
control structure is used in C as part of the switch
statement. It allows the program to check a value against multiple cases and perform different actions based on the result.
Example:
cint num = 2;
switch(num) {
case 1:
printf("One\n");
break;
case 2:
printf("Two\n");
break;
case 3:
printf("Three\n");
break;
default:
printf("Invalid number\n");
break;
}
Output: Two
Explanation: The switch
statement checks the value of num
against each case. Since num
is equal to 2, the second case is executed, printing "Two".
- Decisions Using switch:
The switch
statement is used in C to make decisions based on the value of a single variable or expression. It can be used as an alternative to a long if-else
statement.
Example:
cchar grade = 'B';
switch(grade) {
case 'A':
printf("Excellent\n");
break;
case 'B':
printf("Good job\n"); break;
case 'C':
printf("Good\n");
break;
case 'D':
printf("Needs Improvement\n");
break;
default:
printf("Invalid grade\n");
break;
}
Output: Good job
Explanation: The switch
statement checks the value of grade
against each case. Since grade
is equal to 'B', the second case is executed, printing "Good job".
- Tips and Traps:
When using the switch
statement, it's important to remember to include a break
statement after each case to prevent the program from executing additional cases. If a break
statement is not included, the program will continue to execute the code for each subsequent case.
- switch Versus if-else Ladder:
The switch
statement can be used as an alternative to a long if-else
ladder when checking a single variable against multiple conditions. It can make the code more readable and easier to maintain.
Example:
cint num = 5;
if (num == 1) {
printf("One\n");
}
else if (num == 2) {
printf("Two\n");
}
else if (num == 3) {
printf("Three\n");
}
else {
printf("Invalid number\n");
}
Output: Invalid number
Example using switch:
cint num = 5;
switch(num) {
case 1:
printf("One\n");
break;
case 2:
printf("Two\n");
break;
case 3:
printf("Three\n");
break;
default:
printf("Invalid number\n");
break;
}
Output: Invalid number
- The goto Keyword:
The goto
keyword in C is used to transfer control to a labeled statement within the same function. However, it can make the code harder to understand and maintain, and should generally be avoided.
Example:
cfor (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 10; j++) {
if (i * j == 25) {
goto found;
}
}
}
printf("Number not found\n");
goto end;
found:
printf("Number found at %d, %d\n", i, j);
end:
printf("end");
No comments:
Post a Comment
Tell us how you like it.