Switch, Break and Continue in C
Switch Statement
Switch case is used for control statements which decides the execution of statements rather than if-else statements.In other word, Switch Case is utilized when there are several cases and each requires a different task to be completed.
Switch:
- Switch statement is used as a control statement which allows the execution of multiple conditions for the multiple possible values of a single variable.
Break:
- Break statement is used to stop the process or execution of code. It works as an exit statement.
Continue:
- Continue statement is also known as the jump statement. It is used to skip a segment of code.
Syntax:
switch(expression) { case 1: statement(s); break; case 2: statement(s); break; default: statement(s); }
Algorithm:
Step 1: Start
Step 2: Initialize value
Step 3: Check the expression
Step 4: If expression is true for given case, then execute the statement.
Step 5: If expression is false, then use default statements.
Step 6: Stop
Rules of Switch Statement:
- Switch expression needs to be of the character or integer type.
- Case value of switch statement must include an integer or character constant.
- Each case in switch statement should have unique value.
- Case value of switch statement can be used only inside the switch statement.
- In the switch expression, the break statement is not required.
- If all cases will be executed, there will be no chance to use break statements.
- In switch statements if the cases are not matched to the given condition the system automatically uses the default case.
In switch statement, break statement is used as a keyword in C which brings the program control out of the loop or given condition.
Example 1
Run
#include <stdio.h> int main() { int a = 3; switch (a) { case 1: printf("1"); break; case 2: printf("2"); break; case 3: printf("3"); break; case 4: printf("4"); break; default: printf("Other than 1, 2, 3 and 4"); break; } return 0; }
Output:
3
Example 2:
Run
#include <stdio.h> int main() { int i; for(i=1; i<=10; i++){ if(i==4 || i==7) { continue; } else{ printf("%d\n",i); } } return 0; }
Output:
1 2 3 5 6 8 9 10
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment