In C programming, the if-else statement is used for decision-making. it helps us to chain the multiple conditions using the `if-else if-else` statement in C language.
It also allows multiple if-else statements to be nested within each other to handle more complex decision-making scenarios. It helps us to execute certain code blocks based on conditions.
Here's the basic syntax:
if (condition) { // Code to be executed if the condition is true } else { // Code to be executed if the condition is false }
#include <stdio.h> int main() { int num = 10; if (num > 0) { printf("The number is positive.\n"); } else { printf("The number is non-positive.\n"); } return 0; }
The "condition" is an expression that evaluates to either true or false.
If the "condition" evaluates to "true", the code block immediately following the "if" statement is executed.
If the "condition" evaluates to "false", the code block following the "else" statement is executed.
Note: if "num" is greater than "0", it prints "The number is positive.", otherwise, it prints "The number is non-positive.".
#include <stdio.h> int main() { int num = 10; if (num > 0) { printf("The number is positive.\n"); } else if (num < 0) { printf("The number is negative.\n"); } else { printf("The number is zero.\n"); } return 0; }
We can also chain multiple if-else statements together, creating more complex decision-making logic:
#include <stdio.h> int main() { int num = 10; if (num % 5 == 0) { printf("The number is divisible by 5.\n"); if (num % 2 == 0) { printf("The number is also divisible by 2.\n"); } else { printf("The number is not divisible by 2.\n"); } } else if (num < 0) { printf("The number is negative.\n"); } else { printf("The number is zero.\n"); } return 0; }
If "num" is greater than 0, it prints "The number is positive."
If "num" is less than 0, it prints "The number is negative."
If "num" is equal to 0, it prints "The number is zero."
We can also chain multiple if-else statements together, to create nested if-else statements for complex decision-making logic.
If "num" is completely divisible by 5, so it will enter into the condition and prints "The number is divisible by 5."
Then, it checks that "num" is completely divisible by 2, so it will enter into the condition and print "The number is also divisible by 2." Otherwise it will print "The number is not divisible by 2".