Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CSHARP

c# logical operators

// Logical operators are a way for us to make our programs
// more efficient and clean to read.

// instead of a lot of if statements inside eachother
// logical operators allow us to check a couple of boolean expressions
// in a single if statement

// We have 3 logical operators: not (!), and (&&), or (||)
// let's see an example of them being used.
int num = 25;
bool isNumEven = num % 2 == 0;

// Not operator (!)
if (!isNumEven){
  Console.WriteLine("not operator");
  // if the value of the boolean variable/expression is false
  // the not operator will make the if statement true basically
  // like it's flipping the values
}

// And operator (&&)
if (num - 5 == 20 && Math.Sqrt(num) == 5){
  Console.WriteLine("And operator");
  // only if both expressions are true the if will return
  // true and run the code written inside it.
  // it's enough for one expression to be false for the entire thing 
  // to be false
}

// or operator (||)
if (num % 10 == 0 || num % 10 == 5){
  Console.WriteLine("Or operator");
  // if only one expression is true the if will return
  // true and run the code written inside it.
  // but if all expressions are false the if will return false
}
 
PREVIOUS NEXT
Tagged: #logical #operators
ADD COMMENT
Topic
Name
7+1 =