If-Else Statements in C

Conditional statements in C allow programs to make decisions based on certain conditions. The if and else statements help control program flow based on logical conditions. This tutorial covers the basics of using if, else, and else if statements.

Step 1: Understanding If-Else Syntax

The basic syntax of an if statement in C is:

if (condition) {
        // Code executes if condition is true
    }

Adding an else statement allows for alternate execution:

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

Step 2: Writing a Simple If Statement

Let's create a program that checks if a number is positive:

#include <stdio.h>

    int main() {
        int number = 10;

        if (number > 0) {
            printf("The number is positive.\n");
        }

        return 0;
    }

Step 3: Using If-Else

If the condition is false, we use else to handle the alternative case:

#include <stdio.h>

    int main() {
        int number = -5;

        if (number > 0) {
            printf("The number is positive.\n");
        } else {
            printf("The number is not positive.\n");
        }

        return 0;
    }

Step 4: Adding Else If

The else if statement allows multiple conditions:

#include <stdio.h>

    int main() {
        int number = 0;

        if (number > 0) {
            printf("The number is positive.\n");
        } else if (number == 0) {
            printf("The number is zero.\n");
        } else {
            printf("The number is negative.\n");
        }

        return 0;
    }

Step 5: Using Logical Operators

Logical operators like && (AND), || (OR), and ! (NOT) can combine conditions:

#include <stdio.h>

    int main() {
        int age = 20;

        if (age >= 18 && age <= 65) {
            printf("You are an adult.\n");
        } else {
            printf("You are either too young or a senior.\n");
        }

        return 0;
    }

Step 6: Nested If Statements

If statements can be nested for complex logic:

#include <stdio.h>

    int main() {
        int score = 85;

        if (score >= 50) {
            printf("You passed.\n");
            if (score >= 80) {
                printf("You passed with distinction!\n");
            }
        } else {
            printf("You failed.\n");
        }

        return 0;
    }

Step 7: Best Practices

  • Use indentation for readability.
  • Minimize deep nesting to keep code simple.
  • Use else if instead of multiple if statements where possible.

Next Steps

Understanding conditional statements is essential in programming. Try:

  • Writing a program that checks for even and odd numbers.
  • Creating a grading system based on score ranges.
  • Using conditions in loops for complex logic.

For further learning, check out the C Programming Tutorial.