What is if else statement in c- Definition, syntax, flow chart and examples

What is if else statement in c- Definition, syntax, flow chart and examples

if else statement in c

 if else is a decision making statement. which can handle both expected as well unexpected situation. in this control structure first if statement is evaluated if it is true statement along it will execute otherwise statement along else will execute.

Syntax of if else statement 

if(condition)

{

statement 1;

}

else

{

statement 2;

}

In this case, if the condition is true then the statement 1 is executed otherwise statement 2 is executed. The else portion of the if else statement is optional

Flow chart of if else statement

Flow chart of if else statement




How does if else work 

The first condition must be given if the condition is true then if will be executed or the expected situation will be executed otherwise else statement or unexpected statement will be executed

Example of if else statement

C program to print given number is odd or even

#include<stdio.h>

#include<conio.h>

void main()

{

int n;

printf("\n Enter the number");

scanf("%d",&n);

if(n%2==0)

{

printf("%d is even number",n);

}

else

{

printf("%d is odd number",n);

}

getch();

}

Output







Here in this example, first user have to give a number. And condition is checked here if(n%2),  the condition is evaluated because the even number is always divisible by 2. If the condition is true than printf("\n %d is even number ",n); is execute.

Otherwise printf("%d is even number",n); is executed.

Here user give 8 and program check condition as 8%2==0 which is true and printf("\n %d is even number",n); part display 8 is even number.

Another example user give 9 and program check condition as 9%2==0 which is false and printf("%d is odd number",n); is execute.

Let see another example 

C program to check if first number is exactly divisible or not

#include<stdio.h>

#include<conio.h>

void main()

{

int a, b;

printf("\n Enter two number");

scanf("%d%d",&a,&b); 

if(a%2==0)

{

printf("\n %d is exactly divisible by %d",a,b);

}

else 

{

printf("\n %d is not exactly divisible by %d",a,b);

}

getch();

}

Output




For if statement

Click here

For else if ladder statement

Click her

For nested if else statement






Post a Comment

0 Comments