Switch Statement in C Program
In this post, We will learn about switch case statement in the C programming language. The if..else..if ladder allows you to execute a block code among many alternatives. If you are checking on the value of a single variable in if...else...if, it is better to use a switch statement.
Example: Take a character input and find if the input is +, -, * or /.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
In this post, We will learn about switch case statement in the C programming language. The if..else..if ladder allows you to execute a block code among many alternatives. If you are checking on the value of a single variable in if...else...if, it is better to use a switch statement.
Syntax Switch-Case in C
switch (n)
{
case constant1:
// code to be executed if n is equal to constant1;
break;
case constant2:
// code to be executed if n is equal to constant2;
break;
.
.
.
default:
// code to be executed if n doesn't match any constant
}
Example: Take a character input and find if the input is +, -, * or /.
# include <stdio.h>
int main() {
char operator;
printf("Enter an operator (+, -, *, /): ");
scanf("%c", &operator);
switch(operator)
{
case '+':
printf("+ Operator");
break;
case '-':
printf("- Operator");
break;
case '*':
printf("* Operator");
break;
case '/':
printf("/ Operator");
break;
// operator is doesn't match any case constant (+, -, *, /)
default:
printf("Error! operator is not correct");
}
return 0;
}
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Comments
Post a Comment