1)if
The if statement is the most simple decision-making statement. It is used to decide whether a
certain statement or block of statements will be executed or not i.e if a certain condition is true
then a block of statements is executed otherwise not.
Syntax:
if(condition)
{
// Statements to execute if
// condition is true
}
flowchart:
Program:
// C program to illustrate If statement
#include <stdio.h>
int main()
{
int i = 10;
if (i > 15) {
printf("10 is greater than 15");
}
printf("I am Not in if");
}
Output:
I am Not in if
2) if-else
The if statement alone tells us that if a condition is true it will execute a block of statements and if
the condition is false it won’t. But what if we want to do something else when the condition is
false? Here comes the C else statement. We can use the else statement with the if statement to
execute a block of code when the condition is false. The if-else statement consists of two blocks,
one for false expression and one for true expression
Syntax of if else
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
Flowchart of if-else Statement
Program:
// C program to illustrate If statement
#include <stdio.h>
int main()
{
int i = 20;
if (i < 15) {
printf("i is smaller than 15");
}
else {
printf("i is greater than 15");
}
return 0;
}
Output:
i is greater than 15
3) A nested if in C is an if statement that is the target of another if statement. Nested if statements
mean an if statement inside another if statement. Yes, C allow us to nested if statements within if
statements, i.e, we can place an if statement inside another if statement.
Syntax of Nested if
if (condition1)
{
// Executes when condition1 is true
if (condition_2)
{
// statement 1
}
}
Flowchart:
Program:
#include <stdio.h>
int main() {
int num1, num2;
// Input two numbers
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
// First if condition to check if num1 is greater than num2
if (num1 > num2) {
// Nested if to check if num1 is positive
if (num1 > 0) {
printf("num1 (%d) is larger than num2 (%d) and positive.\n", num1, num2);
}
}
return 0;
}
Output:
Enter two numbers: 2 5
4) if-else-if Ladder in C
The if else if statements are used when the user has to decide among multiple options. The C if
statements are executed from the top down. As soon as one of the conditions controlling the if is
true, the statement associated with that if is executed, and the rest of the C else-if ladder is
bypassed. If none of the conditions is true, then the final else statement will be executed. if-else-if
ladder is similar to the switch statement.
Flow chart:
Program:
// C program to illustrate nested-if statement
#include <stdio.h>
int main()
{
int i = 20;
if (i == 10)
printf("i is 10");
else if (i == 15)
printf("i is 15");
else if (i == 20)
printf("i is 20");
else
printf("i is not present");
}
Output:
i is 20