If-else statement

It is a part of decision making on run-time in C

IF:
Here, you have to define a condition after defining ‘if’ in your program. If your condition is true, it will execute the statement that falls under if statement.
Example for if statement:
main()
{
int age=10;
if(age==10)
{
printf(“age is 10”);
}
getch();
Here, if age is 10, it will execute the if blocks, if not then it will skip it.
Output:
age is 10
IF-ELSE
You saw what is ‘if’ statement above, now if your ‘if’ statement is false, the program will skip that block, but if you use ‘else’ statement, it will show the else statement as default statement when the ‘if’ becomes false.
Example of if-else
main()
{
int age=12;
if(age==10)
{
printf(“age is 10”);
}
else
{
printf(“the age isn’t 10”);
}
getch();
Here, if statement doesn’t satisfy, so it will execute else
Output:
the age isn’t 10
IF-ELSE Ladder
Till now we used only one condition, what if there are many conditions? Use if-else ladder.
Example of if-else ladder
main()
{
int age=15;
if(age==10)
{
printf(“age is 10”);
}
else if(age==12)
{
printf(“age is 12”);
}
else if(age==15)
{
printf(“age is 15”);
}
else
{
printf(“age isn’t 10,12 or 15”);
}
getch();
Here it will checkthe statement if every condition and will execute the correct one.
Output:
age is 15
NESTED IF-ELSE
//nested means one within another in programming sense.
If you want that the program should execute a part of the program if it satisfy a particular condition and after that it should satisfy more conditions, nested if-else is for you.
Example of nested if else:
main()
{
int age=8;
if(age>=10)
{
if(age==10)

printf(“age is 10”);
}
else
{
if(age==12)
{
printf(“age is 12”);
}
}
else
{
printf(“age is more not more than 10”);
}
getch();
You will see series of if-else inside another if-else.
Output:
age is more not more than 10
Notes

  • Don’t keep a semicolon after if condition.
  • You will find a need of if-else many times in a real project.
  • Almost every programming language has a concept of If-else but have different syntaxs