Control Statements

C provides two styles of flow control:
- Branching
- Looping
Branching is deciding what actions to take and looping is deciding how often to take some action.
If statement:
If statement takes an expression in parenthesis and a statement or block of statements. If the expression is true, the statement or instruction block is executed or these instructions are skipped. This is the simplest form of branching statements.
If-else statement:
The if…else statement runs two different codes based on whether the test expression is true or false.
Syntax:
if (expression)
statement;
or
if (expression)
{
Block of statements;
}
or
if (expression)
{
Block of statements;
}
else
{
Block of statements;
}
or
if (expression)
{
Block of statements;
}
else if(expression)
{
Block of statements;
}
else
{
Block of statements;
}
Example Program:
#include <stdio.h>
void main()
{
int n;
printf("Enter an integer");
scanf("%d", &n); if(n%2==0)
printf("%d is an even integer",n);
else
printf("%d is an odd integer",n);
}
Nested if-else statement:
Sometimes you must choose between more than two possibilities. The nested if…else statement lets you verify several test expressions and run different codes for more than two conditions.
Syntax:
if (testExpression1)
{
//statements to run if testExpression1 is correct.
}
else if(testExpression2)
{
// statements to run if testExpression1 is false and testExpression2 is true
}
else if (testExpression 3)
{
// statements to run if testExpression1 and testExpression2 is false and testExpression 3 is true.
}
.
.
else
{
// statements to run if all test expressions are false
}
Example Program:
#include <stdio.h>
void main()
{
int n1, n2;
printf("Enter two integers:");
scanf("%d %d", &n1, &n2);
if(n1==n2) // checks if two integers are equal
{
printf("%d=%d",n1,n2);
}
else if(n1>n2) // checks if number1 is greater than number2.
{
printf("%d > %d",n1,n2);
}
else
{
printf("%d < %d",n1,n2); // if both test expression is false
}}