if else statement in c programming

Given Diagram is for the syntax and flowchart of the if-else statement.
lets learn how syntax (if else statement) works from given Diagram.
We know that program execution starts from top and goes to end.
After step by step successful execution of program the control falls into the if block.
after that The flow jumps to Condition.
and starts testing the Condition
1. if the condition tested is true. or its result is true then executes statements inside if body.
i.e. //body of if
/* statements to be
executed when
conditions in if is true */

after successful execution of above code the control comes out of the code and executes the code "Statements outside if-else".

2. if the condition tested is false. then the code or statements inside else executes i.e. "statements in else"
"statements outside if" always executes if the condition is true or false.


Example 1: C program to illustrates the use of if-else statement .

/* C program to check Given number is even or odd using if else statement */
#include<stdio.h>
int main()
{
int x;
printf("\n Enter any number");
scanf("%d",&x);
if(x%2==0)    /*test-condition */
{
printf("\n %d is even number",x);
}
else    /*else executes when condition is false */
{
printf("\n %d is odd number",x);
}
return 0;
}

Output:
Enter any number
7
7 is odd number.
Program Explanation:
The above program illustrates the use of if-else statement to check given number is odd or even.
1. In the above program, we have declared integer variables int x ; to store numeric value.
2. Then, we have used printf("\n Enter any number");
scanf("%d",&x);
Which shows the message "Enter any number" on console and control waits until we do not enter any number, but here we have entere number is 7
which is get stored in variable x in memory by scanf("%d",&x);
3. Then, we have used if with a test-expression to check whether the number is the even or odd by using if(x%2==0).
Here the test expression evaluates (7%2 gives remainder i.e. 1 hence x%2==0 is false) false .
4. Thus condition is false in if block so else block going to be execute.
Statements inside else is executed .
i.e. printf("\n %d is is odd number",x);
which gives the final output: " 7 is odd"
%d is the format specifier which is the place holder for integer value,so here value of x is placed at %d hence output "7 is odd"


Previous Topic:-->> if statement in C || Next topic:-->>if else if ladder in C.