Conditions in C If Statements: Logic Operators & Nesting

目次

1. Introduction

Conditional branching in the C language is an essential element for controlling the flow of a program. Among them, the if statement is a fundamental structure for executing different actions based on conditions. However, in real programs, there are many situations where it is necessary to combine multiple conditions rather than just a single one. For example, consider the following situation.
Example: “If variable a is 10 or greater, and b is less than 5, then execute the process”
In such cases, C allows you to combine conditions using logical operators (&&, ||) and nesting (nested if statements). This article provides a detailed explanation, from basics to advanced topics, on how to handle multiple conditions with C’s if statements.

2. Basics of C Language if Statements

2.1. Basic Structure of if Statements

In C, an if statement executes a specific block of code when the given condition is true.
if (condition) {
    // Code to execute when the condition is true
}

Example: Display a message if variable x is 10 or greater

#include <.h>

int main() {
    int x = 15;

    if (x >= 10) {
        printf("x is 10 or greater.\n");
    }

    return 0;
}

2.2. Basic Structure of if-else Statements

Adding else to an if statement allows you to specify the code to run when the condition is false.
if (condition) {
    // Code to execute when the condition is true
} else {
    // Code to execute when the condition is false
}

Example: Determine whether the number entered by the user is positive

#include <stdio.h>

int main() {
    int num;
    printf("Please enter an integer: ");
    scanf("%d", &num);

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

    return 0;
}

2.3. Basic Structure of if-else if-else Statements

Use else if when you need to check multiple conditions.
if (condition1) {
    // Code to execute when condition 1 is true
} else if (condition2) {
    // Code to execute when condition 2 is true
} else {
    // Code to execute when all conditions are false
}

Example: Display a grade based on the entered score

#include <stdio.h>

int main() {
    int score;
    printf("Please enter the score: ");
    scanf("%d", &score);

    if (score >= 80) {
        printf("Grade: A\n");
    } else if (score >= 60) {
        printf("Grade: B\n");
    } else {
        printf("Grade: C\n");
    }

    return 0;
}

3. How to handle multiple conditions with if statements

3.1. Using logical operators (&&, ||)

In C, you can combine multiple conditions using the && (AND operator) and || (OR operator). ✅ && (AND operator)
  • Executed when all conditions are met
#include <stdio.h>

int main() {
    int a = 15, b = 3;

    if (a > 10 && b < 5) {
        printf("a is greater than 10 and b is less than 5.
");
    }

    return 0;
}
|| (OR operator)
  • Executed if either condition is met
#include <stdio.h>

int main() {
    int a = 8, b = 3;

    if (a > 10 || b < 5) {
        printf("a is greater than 10 or b is less than 5.
");
    }

    return 0;
}
! (NOT operator)
  • Inverts the condition
#include <stdio.h>

int main() {
    int a = 8;

    if (!(a > 10)) {
        printf("a is 10 or less.
");
    }

    return 0;
}

3.2. Nesting if statements

  • By placing an if statement inside another if, you can create finer-grained branching

Example: Checking both age and height

#include <stdio.h>

int main() {
    int age = 20, height = 170;

    if (age >= 18) {
        if (height >= 160) {
            printf("You are an adult and at least 160 cm tall.
");
        } else {
            printf("You are an adult but under 160 cm tall.
");
        }
    } else {
        printf("You are a minor.
");
    }

    return 0;
}

4. Best Practices for Handling Multiple Conditions

4.1. Improving Readability

4.1.1. Splitting Conditional Expressions

int isEligibleForDiscount = (score >= 80);
int isAdult = (age >= 18);
int isMemberValid = (isMember == 1);

if (isEligibleForDiscount && isAdult && isMemberValid) {
    printf("You are eligible for the discount.\n");
}

4.1.2. Encapsulating Conditional Logic in a Function

#include <stdio.h>

int isEligible(int score, int age, int isMember) {
    return (score >= 80 && age >= 18 && isMember == 1);
}

int main() {
    int score = 85, age = 20, isMember = 1;

    if (isEligible(score, age, isMember)) {
        printf("You are eligible for the discount.\n");
    } else {
        printf("You are not eligible for the discount.\n");
    }

    return 0;
}

4.2. Performance Considerations

4.2.1. Leveraging Short-Circuit Evaluation

if (a != 0 && b / a > 1) {
    printf("Result: %d\n", b / a);
}

4.2.2. Optimizing Evaluation Order

if (a > 0 && isHeavyCalculation()) {
    printf("Executing process\n");
}

4.3. Improving Maintainability

4.3.1. Emphasizing Clarity of Conditional Expressions

if (user.age >= 18 && user.score >= 50) {
    printf("Conditions met.\n");
}

4.3.2. Avoiding Magic Numbers

#define ADULT_AGE 18

if (age >= ADULT_AGE) {
    printf("Adult.\n");
}

5. Practical Example: Program Using if Statements

5.1. Display Message Based on User’s Age

#include <stdio.h>

int main() {
    int age;

    printf("Please enter your age: ");
    scanf("%d", &age);

    if (age >= 18 && age < 65) {
        printf("You are an adult.
");
    } else if (age >= 65) {
        printf("You are a senior.
");
    } else {
        printf("You are a minor.
");
    }

    return 0;
}

5.2. Simple Login Authentication Program

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

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

    printf("Username: ");
    scanf("%s", username);

    printf("Password: ");
    scanf("%s", password);

    if (strcmp(username, "admin") == 0 && strcmp(password, "1234") == 0) {
        printf("Login successful!
");
    } else {
        printf("Login failed...
");
    }

    return 0;
}

5.3. Triangle Classification Program

#include <stdio.h>

int main() {
    int a, b, c;

    printf("Please enter the three sides of the triangle: ");
    scanf("%d %d %d", &a, &b, &c);

    if (a == b && b == c) {
        printf("It is an equilateral triangle.
");
    } else if (a == b || b == c || a == c) {
        printf("It is an isosceles triangle.
");
    } else {
        printf("It is a scalene triangle.
");
    }

    return 0;
}

5.4. Numeric Range Check

#include <stdio.h>

int main() {
    int number;

    printf("Please enter a number: ");
    scanf("%d", &number);

    if (number >= 50 && number <= 100) {
        printf("The number is appropriate.
");
    } else {
        printf("Out of range.
");
    }

    return 0;
}

6. FAQ (Frequently Asked Questions)

6.1. Which should be used, if statements or switch statements?

When to use if statements

  • When a range (greater/lesser comparison) is needed
  • When using complex logical expressions
if (score >= 90) {
    printf("Grade: A
");
} else if (score >= 80) {
    printf("Grade: B
");
} else {
    printf("Grade: C
");
}

When to use switch statements

  • When evaluating specific values (integers or characters)
switch (grade) {
    case 'A':
        printf("Excellent.
");
        break;
    case 'B':
        printf("Good grade.
");
        break;
    default:
        printf("Invalid rating.
");
}

6.2. Should you use nested if statements or logical operators?

When using nesting

if (age >= 18) {
    if (hasID) {
        printf("You may enter.
");
    } else {
        printf("Identification is required.
");
    }
}

When using logical operators

if (age >= 18 && hasID) {
    printf("You may enter.
");
}

6.3. How to write if conditions simply

Using the ternary operator

int result = (a > 10) ? 1 : 0;

Encapsulating the condition in a function

int isAdult(int age) {
    return age >= 18;
}

if (isAdult(age)) {
    printf("You are an adult.
");
}

6.4. Causes when an if condition is wrong and doesn’t work

= (assignment operator) and == (comparison operator) mistake

if (x == 5) {
    printf("x is 5.
");
}

Explicitly specify condition precedence

if ((a > 10 && b < 5) || c == 3) {
    printf("Condition met
");
}

Floating-point comparison

#include <math.h>

if (fabs(a - b) < 0.0001) {
    printf("a and b are almost equal.
");
}

7. Summary

7.1. Basic Structure of if Statements

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

7.2. How to Handle Multiple Conditions in if Statements

Using Logical Operators

if (age >= 18 && hasID) {
    printf("You may enter.
");
}

Using Nesting

if (age >= 18) {
    if (hasID) {
        printf("You may enter.
");
    } else {
        printf("ID is required.
");
    }
}

7.3. Writing Style Considering Readability and Performance

Encapsulating Conditions in Functions

int isEligible(int score, int age) {
    return (score >= 80 && age >= 18);
}

if (isEligible(85, 20)) {
    printf("Eligible for benefits.
");
}

Using Short-Circuit Evaluation

if (a != 0 && b / a > 1) {
    printf("Result: %d
", b / a);
}

7.4. Practical Usage Examples

if (age >= 18 && age < 65) {
    printf("You are an adult.
");
}
if (strcmp(username, "admin") == 0 && strcmp(password, "1234") == 0) {
    printf("Login successful!
");
}
if (number >= 50 && number <= 100) {
    printf("The number is appropriate.
");
}

7.5. Common Mistakes and Their Countermeasures

if (x == 5) {
    printf("x is 5.
");
}
if ((a > 10 && b < 5) || c == 3) {
    printf("Condition met
");
}
#include <math.h>

if (fabs(a - b) < 0.0001) {
    printf("a and b are almost equal.
");
}

7.6. Summary of This Article

✅ Mastering C’s if statements makes program control more flexible! ✅ Use logical operators and nesting appropriately to combine multiple conditions! ✅ Keep readability and performance in mind to optimize your code! ✅ Write correctly while preventing errors through practical examples!

7.7. Looking Ahead to Future Learning

In the future, by learning more advanced control structures (such as switch statements, while loops, etc.) and the use of functions, you will be able to create even more flexible programs. Hone your C language skills and aim for better programming!
侍エンジニア塾