Smile

Thursday, September 29, 2011

Control Statements

By default the instructions in a program are executed sequentially.
Many a times, we want a set of instructions to be executed in one
situation, and an entirely different set of instructions to be
executed in another situation. This kind of situation is dealt in
C programs using a decision control instruction. As mentioned
earlier, a decision control instruction can be implemented in C using:
(a) The if statement

(b) The if-else statement

(c) The conditional operators

(d) The else-if ladder (e) The switch statement


The if Statement
Like most languages, C uses the keyword if to implement the
decision control instruction. The general form of if statement looks
like this:
Syntax
if ( this condition is true )
{
execute these statements;
}

Flow Diagram of if statement

The if-else Statement
This is also said to be two way decision control statements. The general form of if statement looks like this:
Syntax
if ( this condition is true )
{
execute these statements ;
}
else
{
execute these statements;
}

Flow Diagram of
if-else statement




Conditional operator (or) Ternary Operator

The conditional operator is unusual in that it takes three operands. The syntax of this operator is like this:

Condition ? Expression1 : Expression2;

You can think of the conditional operator as if it were a function that works like this:
if ( Condition )

return Expression1;
else
return Expression2;

The Condition expression must evaluate to true or false. If it is true Expression1 is evaluated and its value is returned. If Condition is false Expression2 is evaluated and its value is returned. Both Expression1 and Expression2 must be the same type (or convertible to the same type).

Example
int a=101,b=50,c;
c=a>b?10:20;
The else if ladder
This is also said to be two way decision control statements. The general form of if statement looks like this:
Syntax
if ( this condition is true )
{
execute these statements ;
}
else if ( this condition is true )
{
execute these statements ;
}
else if ( this condition is true )
{
execute these statements ;
}
.
.
.
else
{
execute these statements ;
}

Flow Diagram of else-if ladder