- A selection statement is a control statement that allows choosing between two or more execution paths in a program.
- C provide one-way, two-way and multiple conditional branching execution.
- C provides this branching through two methods namely if statement and switch statement
- There are three ways of writing if statements.
if(expression){
Statements;
}
- The expression is evaluated to either true or false.
- True is nonzero value and false is zero value.
- The Statements inside the if will only be executed if the expression is evaluated to true
if(expression){
Statements1;
}else{
Statements2;
}
- If the expression is evaluated to true then Statements1 will be executed.
- If the expression is evaluated to false then Statements2 will be executed.
if(expression1){
Statements1;
}elseif (expression2{
Statements2;
}elseif (expression3){
Statements3;
}else{
Statements4;
}
Switch Statements
- Switch is a composite statement used to make a decision between many alternatives
- The expression of switch statements must be evaluated to either integer type or character constant.
- The selection condition must be one of the C integral types
switch (expression){
case constant-1: statement;
…
statement;
break;
case constant-2: statement;
…
statement;
break;
case constant-n: statement;
…
statement;
break;
default : statement;
…
statement;
break;
}
- Each case label must be a constant expression either integer or character
- The case label simply provides an entry point to start executing the code
- Default is executed whenever none of the other case values matches the value in the switch expression
- The break statement causes the program to jump out of the switch statement; continue with the code after the switch statement
No comments:
Post a Comment