Making a decision in order to execute a group of statements meeting the given conditions or repeat the execution until the conditions are satisfied is called as Decision Making. It can be done by using certain C if statements.
Conceptual
figure
if statements
if
Description
The block of code gets executed only when the condition becomes true otherwise C if block will be skipped.
Syntax
if(condition)
{
//statements
}
Example
[c]
#include<stdio.h>
void main()
{
int a=2,b=1;
if(a>b)
{
printf("a is greater");
}
}[/c]
Output:
[c]a is greater[/c]
if...else
Description
The block of code will be executed only when the given if condition is true otherwise compiler executes the statements of else block.
[c]#include<stdio.h>
void main( )
{
int x,y; x=1; y=0; if (x > y )
{
printf("x is greater than y");
}
else
{
printf("y is greater than x");
}
} [/c]
Output:
[c]x is greater than y[/c]
Nested-if
Description
Nested-if checks more than one condition. In short,nested if is if in if.When the condition of first if statement is false,then compiler checks for next if block. If if statement is true, compiler executes statements in inner if block, otherwise it executes else block statements.
[c]
#include<stdio.h>
int main()
{
int a=10,b=20,c=30;
if (a>b)
{
printf("a is greater than b");
}
if(b>c)
{
printf("b is greater than c");
}
else
{
printf("a is less than c");
}
}
} [/c]
Output:
[c]a is less than c[/c]
Summary
Key Points
if statements helps in decision making.
if block executes only when true.
if-else will have true and false options.
Nested-if will have multiple if and else blocks.
Programming
Tips
C if statement operate on "condition", hence do not leave condition part.
More than one statement in if are enclosed between "{" & "}".
Carefully choose if,if-else, if-else if-else based on the problem.
Better to avoid nested-if as it will result in confusion while understanding the code.