else Statement in C

The else statement in C is used in conjunction with the if statement to execute a block of code when the if condition evaluates to false.

Key Topics

1. Syntax of else Statement

if (condition) {
    // Code to execute if condition is true
} else {
    // Code to execute if condition is false
}

2. Example of else Statement

Example: Checking if a Number is Positive or Negative

#include <stdio.h>

int main() {
    int number = -3;
    if (number >= 0) {
        printf("The number is positive.\n");
    } else {
        printf("The number is negative.\n");
    }
    return 0;
}

Output:

The number is negative.
                

Code Explanation: Since number is -3, the condition number >= 0 is false, so the code inside the else block is executed.

3. Understanding if...else Flow

The if...else statement directs the program flow into one of two paths depending on the condition.

  • If the condition is true, the code inside the if block runs.
  • If the condition is false, the code inside the else block runs.

Best Practices

  • Use the else statement to handle all cases not covered by the if condition.
  • Keep if and else blocks concise and related.
  • Maintain consistent indentation for readability.

Don'ts

  • Don't neglect the else block if there is meaningful code to execute when the condition is false.
  • Don't write unrelated code in the else block.
  • Don't overcomplicate conditions; break them down if necessary.

Key Takeaways

  • The else statement complements the if statement to handle the false condition.
  • Using else ensures that your program can respond appropriately to different inputs.
  • Proper use of if...else enhances the control flow of your program.