2. If statement
The if statement is a powerful decision
making statement and is used to control the
flow of execution of statements.
The if statement can be implemented in
different forms:
1. Simple if statement
2. if….else statement
3. Nested if….else statement
4. else if ladder
3. Simple If statement
The general form of a simple if statement is:
if(condition)
{
statement-block;
}
satement-x;
If the condition is true then statement-block
is executed; otherwise the statement-block
will be skipped and the execution will jump
to the statement-x;
4. If…else statement
The if…else statement is an extension of the
simple if statement. The general form is
if(condition)
{
True-block statement(s)
}
else
{
False-block statement(s)
}
statement-x;
5. Continue..
If the condition is true then the true-block
statement(s) will execute; otherwise the
false-block statement(s) will execute.
Then it will go to statement-x
Ex: if(x>y)
z=x-y;
else
z=y-x;
printf(“%d”,z);
6. Nested If…else statement
When a series of decisions are involved, we may have to use more than one
if…else statement in nested form as follows:
if(condition-1)
{
if(condition-2)
{
statement-1;
}
else
{
statement-2;
}
}
else
{
statement-3;
}
statement-x;
7. Continue…
If condition-1 is false then statement-3 will
be executed; otherwise if continues to
perform the second test.
If the condition-2 is true, then statement-1
will be executed; otherwise statement-2 will
be executed.
Then the control will be transferred to
statement-x.
8. Else If ladder
There is another way of putting ifs together when
multipath decisions are involved. The general
form:
if(condition-1)
statement-1;
else if(condition-2)
statement-2;
-------------
else if(condition-n)
statement-n;
else
default-statement;
statement-x;
9. Continue..
The conditions are evaluated from the top.
As soon as a true condition is found, the
statement associated with it is executed and
the control is transferred to the statement-x.
When all the conditions are false then the
final else containing the default-statement
will be executed.
10. switch statement
Switch is a multiway decision statement. The
general form:
switch(expression)
{
case value-1: block-1;
break;
case value-2: block-2;
break;
-------------
default: default-block;
}
statement-x;
11. Continue…
The expression is an integer expression or
character. Value-1, value-2,… are constants or
constant expression and are known as case
labels. Each of these values should be unique.
When the switch is executed, the value of the
expression is successively compared against the
values value-1, value-2,….If a case is found whose
value matches with the value of the expression,
the block of statements are executed.
The break at the end of each block signals the end
of particular case and causes exit from switch and
transfer control to statement-x.
The default is optional and if no matches occur
then this default-block is executed.