The if-else
statement is a fundamental part of decision-making in C programming. It allows your code to make choices based on certain conditions, making your programs dynamic and flexible.
What is the if-else
Statement?
In simple terms, the if-else
statement lets you execute one block of code if a condition is true and another block if the condition is false.
Syntax
if (condition) {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false
}
How It Works
- The condition inside the parentheses is evaluated.
- If the condition is true (non-zero), the code inside the
if
block runs. - If the condition is false (zero), the code inside the
else
block runs.
Example
#include <stdio.h>
int main() {
int number = 10;
if (number > 5) {
printf("The number is greater than 5.\n");
} else {
printf("The number is 5 or less.\n");
}
return 0;
}
Output:
The number is greater than 5.
Key Points to Remember
- Conditions: Any valid C expression that evaluates to true (non-zero) or false (zero) can be used.
- Else is Optional: You can use
if
withoutelse
if no alternative action is needed.
Example:if (number > 0) { printf("Positive number.\n"); }
- Nesting: You can nest multiple
if-else
statements for complex conditions.
Example:if (number > 0) { printf("Positive number.\n"); } else if (number < 0) { printf("Negative number.\n"); } else { printf("Zero.\n"); }
The if-else
statement is a cornerstone of programming logic. It allows your programs to respond dynamically to different scenarios, making them more robust and interactive.