Selection Structure
A statement is executed when a condition is true and statement is ignored when condition is false, it's also conditional statement. It executes the statement on the basis of conditions.
Types of selection structure
- if-else structure : it is used to execute or skip a statement or set of statement by checking a condition.
- switch structure : it is used when there are many choices available and only one should be executed.
if statement
if is a keyword in c language and it is a decision-making statement. it is used to execute or skip a statement by checking a condition. Condition is given as a relational expression. If condition is true then statement or set of statements after if statement is executed. when condition is false statement is not executed.
Syntax
if(condition)
statement;
This syntax is used for single statement and statements are written in curly brackets { }. The set of statements is also called compound statements.
The syntax for compound statements in if statement is:
if (condition)
{
statement 1;
statement 2;
.
.
statement N;
}
if-else statement
if else statement executes one block of statements when condition is true or false and other is skipped. Both blocks of statement can never be executes or skipped.
Syntax
if (condition)
statement;
else
statement;
if-else-if
if-else-if statement can be used to choose one statement from many statements. There are many options and only one block of statement should be executed.
Syntax
if(condition)
{
block 1;
}
else if (condition)
{
block 2;
}
....
else
{
block N;
}
Nested if
An if statement within an if statement is called nested if. In nested structure, the control enters into the inner if only when the outer condition is true. The increase in the level of nesting increases the complexity of nested if statement.
switch statement
switch statement is another conditional structure and it's good alternative of nested if-else. it is used when their is many choices available and only one should be executed.
Syntax
switch (expression)
{
case val 1:
statements 1;
break;
case val 2:
statements2;
break;
.
.
.
case val n:
statement n;
break;
default:
statements;
}
No comments:
Post a Comment