If-Else Statements

Conditional statements, such as if and else, play a vital role in decision-making within C programs. They allow the execution of different blocks of code based on specified conditions. Let's delve into the syntax and usage of if-else statements.

Basic Syntax of If-Else Statements

#include <stdio.h>

int main() {
    int num = 10;

    // If-else statement
    if (num > 0) {
        printf("Positive number\n");
    } else {
        printf("Non-positive number\n");
    }

    return 0;
}

In this example, if num is greater than 0, the program prints "Positive number"; otherwise, it prints "Non-positive number."

If-Else Statement Structure

Here, the program checks multiple conditions using else if. If num is positive, it prints "Positive number"; if negative, it prints "Negative number"; otherwise, it prints "Zero."

Nested If-Else Statements

Nested if-else statements allow for more complex decision-making structures. In this example, it checks if both a and b are positive, only a is positive, or both are non-positive.

Practical Tips

  • Use if-else statements for simple decision-making scenarios.

  • Utilize else if to handle multiple conditions sequentially.

  • Be cautious with nested if-else statements; they may impact code readability.

Understanding and effectively using if-else statements are essential skills for writing flexible and logic-driven C programs. If you have specific questions or if there are additional topics you'd like to explore, feel free to ask. Happy coding!