Swich Statement in C
switch statement is a control structure used for making decisions based on the value of a variable or expression. It allows you to test a variable against a list of values (cases) and execute a block of code associated with the first matching case. Here's how the switch statement works:
1. The
switchkeyword is followed by an expression (usually a variable) enclosed in parentheses. This expression is evaluated to determine which case to execute.2. Inside the
switchblock, you list one or morecaselabels. Eachcaselabel represents a possible value that the expression might have.3. When the
switchstatement is executed, it compares the value of the expression to eachcaseconstant sequentially.4. If a match is found (i.e., if the expression's value is equal to a
caseconstant), the code block associated with thatcaseis executed.5. The
breakstatement is used to exit theswitchblock. Withoutbreak, the execution would continue into subsequentcaseblocks until abreakis encountered or theswitchblock ends.6. If none of the
casevalues matches the expression, thedefaultblock is executed (if it exists). Thedefaultblock is optional and serves as a fallback.
20230923122748.png)
20230923122838.png)
20230923122939.png)
20230923123007.png)
20230923123256.png)
switch statement:
switch (expression) {
case constant 1:
// Code to be executed if expression equals constant 1
break;
case constant 2:
// Code to be executed if expression equals constant 2
break;
default:
// Code to be executed if no case matches
}In this example, the user enters a number, and the switch statement determines which option was chosen based on the input value. If the input doesn't match any of the cases, the default block is executed.
