Logical Operators Part 3
Part of the Fundamentals section of Coddy's C# journey — lesson 24 of 69.
When checking multiple conditions, the computer stops checking as soon as it knows the final answer (This is called short-circuit evaluation).
For example:
int x = 0;
int y = 5;
bool result = x != 0 && y / x > 2;Here x equals 0, therefore it will not evaluate y / x > 2. If we would reverse the order:
bool result = y / x > 2 && x != 0;This will result in an error because y will be divided by 0 which is illegal in math.
This technique is used to optimize the evaluation of logical expressions. For example:
int a = 0;
int b = 2;
int c = 3;
int d = 5;
bool result = (a > 0 && b < 2) || (c < -5 && d < 10);In this example b < 2 and d < 10 will not be evaluated because a > 0 and c < -5 are both false.
Challenge
BeginnerLet's create a program to decide if it's a good day for solar panel energy production
Initialize these variables:
isSunnywith the value truewindSpeedwith the value 5.4temperaturewith the value 23solarPanelOutputwith the value 9isCloudywith the value false
Create one logical expression that checks ALL of these conditions:
- It's sunny
- The wind speed is less than 10
- The solar panel output is less than 15
- The temperature is above 20 OR there are no clouds
Cheat sheet
Short-circuit evaluation means the computer stops checking conditions as soon as it knows the final answer.
With && (AND), if the first condition is false, the second won't be evaluated:
int x = 0;
int y = 5;
bool result = x != 0 && y / x > 2; // y / x > 2 is not evaluatedWith || (OR), if the first condition is true, the second won't be evaluated:
bool result = (a > 0 && b < 2) || (c < -5 && d < 10);
// If a > 0 is false, then b < 2 won't be evaluated
// If the first part is false but c < -5 is also false, then d < 10 won't be evaluatedThis optimization prevents unnecessary calculations and can avoid errors like division by zero.
Try it yourself
using System;
public class Program {
public static void Main(string[] args) {
// Initialize variables
// The complete logical expression
bool result =
// Don't delete the lines below
Console.WriteLine("Checking conditions for solar energy production...");
Console.WriteLine("1. Is it sunny? " + isSunny);
Console.WriteLine("2. Is wind speed safe? " + (windSpeed < 10));
Console.WriteLine("3. Can panels produce more? " + (solarPanelOutput < 15));
Console.WriteLine("4. Is temperature good OR no clouds? " + (temperature > 20 || !isCloudy));
Console.WriteLine("\nFinal result - Good day for solar energy production: " + result);
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic Shortcuts5Operators Part 2
Comparison OperatorsLogical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3