If-Else Statement in C
The if-else statement in C is used to execute a block of code based on a condition. If the condition is true, the 'if' block executes; otherwise, the 'else' block executes.
Syntax
if (condition) { // Code executed if condition is true } else { // Code executed if condition is false }
Example
int number = 10; if (number % 2 == 0) { printf("%d is even", number); } else { printf("%d is odd", number); }
How It Works
- The condition inside parentheses is evaluated first.
- If the condition is true (non-zero), the 'if' block runs.
- If the condition is false (zero), the 'else' block runs.
- The else block is optional.
Nested If-Else
You can place an if-else statement inside another if-else to check multiple conditions.
- Example: int marks = 75; if (marks >= 90) { printf("Grade A"); } else if (marks >= 75) { printf("Grade B"); } else { printf("Grade C"); }
Tips
- Always use braces `{}` to avoid errors, even for single statements.
- Keep conditions simple and readable.
- Use nested if-else sparingly to reduce complexity.
- Consider using switch statements for multiple constant comparisons.
Common Mistakes
- Using `=` (assignment) instead of `==` (equality) in conditions.
- Omitting braces `{}` for multi-line statements.
- Confusing the order of if, else if, and else blocks.
- Writing complex conditions without parentheses, leading to unexpected results.
Codecrown