Switch statement in c programming language
- Get link
- X
- Other Apps
Switch statement in c programming language
What Is a switch statement?
The switch statement is a conditional statement that we use to run different code sections based on some conditions. The switch statement also works like the if else-if else ladder statement. As we know in the else-if ladder statement we implement multiple conditions it is exactly how the switch statement works. In the switch statement, we use the term case: that tells us about any specific condition within the switch expression area switch(expression).
What is the syntax of a switch statement in c programming
switch(Some_Epression)
{
case value1:
// insert code here
break;
case value2:
// insert code here
break;
default:
// insert code here
}
Rules and regulations of switch statement:
Always remember that the expressions that are used within the switch statement i.e. switch(expression), this expression must be a single character or an integer value. As discussed earlier case: statements are used in switch statements, these cases must be an integer or a single character. At the end of each case coding block, we use a break statement.
It is not mandatory to write a break statement but it Is a good practice to use a break statement, because if there is no break statement used between different cases then all cases will run or be executed one by one.
What is the default keyword in the switch statement:
We use this default keyword at the end of the switch statement. This default keyword works in the same way as the else statement works in the if else-if else ladder statement. In switch when no case is true then at-last the default case runs and executes some piece of code.
Example of switch statement:
In the above coding example, the main scenario is that we have a variable that we named as num and the datatype of this variable is int.
We assigned the value of 2 to this num variable. Then we used this num variable inside the switch statement.
Now three case statements are used with integer values like 1, 2, and 3 i.e. case 1:, case 2:, and case 3: are used in the above given piece of code.
case 1: means that if the value of the num variable is 1, then run case 1: code, and the same applies to the other two cases with respect to their values.
And if we notice break statement is used between each case to execute only one case at a time.
At last, a default statement is used which will execute if none of the cases are true.
Congratulations you have implemented the switch statement with an example.
- Get link
- X
- Other Apps
Comments
Post a Comment