Real Examples of if...else in C

Understanding how to use if, else if, and else statements in real-world scenarios is crucial for effective programming. Below are different scenarios demonstrating their use.

Key Examples

1. Login System Simulation

This example simulates a simple login system where a user must enter the correct username and password.

#include <stdio.h>
#include <string.h>

int main() {
    char username[20];
    char password[20];

    printf("Enter username: ");
    scanf("%s", username);
    printf("Enter password: ");
    scanf("%s", password);

    if (strcmp(username, "admin") == 0) {
        if (strcmp(password, "1234") == 0) {
            printf("Login successful!\n");
        } else {
            printf("Incorrect password.\n");
        }
    } else {
        printf("User not found.\n");
    }
    return 0;
}

2. Checking for a Leap Year

This program determines whether a given year is a leap year.

#include <stdio.h>

int main() {
    int year;
    printf("Enter a year: ");
    scanf("%d", &year);

    if (year % 4 == 0) {
        if (year % 100 == 0) {
            if (year % 400 == 0) {
                printf("%d is a leap year.\n", year);
            } else {
                printf("%d is not a leap year.\n", year);
            }
        } else {
            printf("%d is a leap year.\n", year);
        }
    } else {
        printf("%d is not a leap year.\n", year);
    }
    return 0;
}

3. Classifying a Number

This example classifies a number as positive, negative, or zero.

#include <stdio.h>

int main() {
    int num;
    printf("Enter a number: ");
    scanf("%d", &num);

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

Key Takeaways

  • Real-world examples help in understanding the practical applications of if...else statements.
  • Nesting if statements allows for more granular control over program flow.
  • Proper input validation and error handling are essential in programming.