3️⃣

3.3 Logical Operators

 

3.3 Logical Operators

Logical operators are used for decision-making. Depending on whether all your statements are true, all your statements are false, or a mix of both, you would want to do different things. The chart below contains the different types of logical operators you can use in C:
 
notion image
 
When using these operators, it is important to remember that 0 represents false, and 1 represents true. Refer to the examples below:
 
int num = (10 == 3) && (10 > 3);
 
In this case, num would save the value of 0 because one of the statements is false → 10 is not equal to 3. Even though the second statement is true, the AND operator (&&) will only return 1, or true, if both statements are correct.
 
int num = (10 == 3) || (10 > 3);
 
in this case, num would save the value of 1 because one statement is true → 10 is greater than 3. Even though the first statement is false, the OR operators (||) will return true, or 1, as long as one statement is correct.
 
int num = 3; int num1 = !(num == 3);
 
In this case, num1 would save the value of 0 because the statement is false → the ! operators means that the variable will save the opposite of the statement that follows. Since num does equal 3, the statement is true. Because we are taking the opposite of that, we would save 0, or false, which is the opposite of true.
 

Previous Section

Next Section

 
⚖️
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.