if-else statements in C Language:
If-Else in C
The if-else
statements in C are used to perform different actions based on different conditions. They can be used in various forms to control the flow of a program.
If Statement
The if
statement is used to execute a block of code if a specified condition is true.
#include
int main() {
int a = 10;
if (a > 0) {
printf("a is positive.\n");
}
return 0;
}
If-Else Statement
The if-else
statement is used to execute one block of code if a specified condition is true, and another block of code if the condition is false.
#include
int main() {
int a = -10;
if (a > 0) {
printf("a is positive.\n");
} else {
printf("a is not positive.\n");
}
return 0;
}
Nesting of If
Nesting of if
statements means using one if
statement inside another if
statement.
#include
int main() {
int a = 5;
int b = 20;
if (a > 0) {
if (b > 0) {
printf("Both a and b are positive.\n");
}
}
return 0;
}
Nesting of Else
Nesting of else
statements means using one else
statement inside another else
statement.
#include
int main() {
int a = -5;
int b = 20;
if (a > 0) {
printf("a is positive.\n");
} else {
if (b > 0) {
printf("a is not positive, but b is positive.\n");
} else {
printf("Neither a nor b are positive.\n");
}
}
return 0;
}
Simplifying Nesting of If using Logical AND
You can simplify the nesting of if
statements using the logical AND operator &&
.
#include
int main() {
int a = 5;
int b = 20;
if (a > 0 && b > 0) {
printf("Both a and b are positive.\n");
}
return 0;
}
Simplifying Nesting of Else using Else If
You can simplify the nesting of else
statements using else if
.
#include
int main() {
int a = -5;
int b = 20;
if (a > 0) {
printf("a is positive.\n");
} else if (b > 0) {
printf("a is not positive, but b is positive.\n");
} else {
printf("Neither a nor b are positive.\n");
}
return 0;
}