Home >Backend Development >C++ >How to determine multiple conditions using if statement in C language?

How to determine multiple conditions using if statement in C language?

WBOY
WBOYOriginal
2024-03-29 13:27:021151browse

How to determine multiple conditions using if statement in C language?

The if statement in C language can determine multiple conditions by using logical operators. Commonly used logical operators include AND (&&), OR (||), NOT (!), etc. The following will use specific code examples to demonstrate how to use if statements to determine multiple conditions in C language.

Suppose there is a requirement: determine whether a student's score is greater than or equal to 60 points and less than or equal to 100 points. If the conditions are met, output "pass", otherwise output "fail". The code is as follows:

#include <stdio.h>

int main() {
    int score = 75;

    if (score >= 60 && score <= 100) {
        printf("及格
");
    } else {
        printf("不及格
");
    }

    return 0;
}

In the above code, use the logical AND (&&) operator to connect the two conditions score >= 60 and score means that when these two conditions are met, the condition of the if statement is established and the corresponding output statement is executed.

In addition to the logical AND operator, you can also use the logical OR (||) operator to determine multiple conditions in an if statement. The following example demonstrates code to determine whether a number is positive or even:

#include <stdio.h>

int main() {
    int num = 6;

    if (num > 0 || num % 2 == 0) {
        printf("%d是正数或偶数
", num);
    } else {
        printf("%d不是正数或偶数
", num);
    }

    return 0;
}

In this code, use the logical OR (||) operator to combine two conditions num > 0 and num % 2 == 0 are connected, indicating that the code in the if statement can be executed when one of the conditions is met.

Through the above examples, we can see how to use logical operators in C language to realize the judgment of multiple conditions in the if statement. Using appropriate logical operators can handle complex conditional judgment logic concisely and efficiently, improving the readability and maintainability of the code.

The above is the detailed content of How to determine multiple conditions using if statement in C language?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn