Comparison operators
Learn to compare values with ==, !=, <, >, <= and >=.
Logical operators
With logical operators you combine multiple conditions: && AND, || OR, ! NOT. All of them produce a bool value.
For example, entering a cinema requires age 18 or older AND a ticket: (age >= 18) && hasTicket. Both conditions must be true for the result to be true. With ||, a single true is enough.
Short-circuit evaluation
The && and || operators short-circuit: if the left side already decides the result, the right side is never evaluated. false && x is false; x is not computed.
This is especially useful to avoid errors like division by zero. Writing (divisor != 0) && (number / divisor > 1) means the second condition is skipped when the divisor is zero, so the program does not crash.
Exercise Write the entry condition
Write an if with the condition (age >= 18) && hasTicket. Print "allowed" when true and "denied" when false. You must use an else branch and the && logical operator.
Show example solution
For the condition, write if ((age >= 18) && hasTicket) { ... } else { ... }.
Example solution:
using System;
class Program
{
static void Main()
{
int age = 20;
bool hasTicket = true;
// Write the condition and print
if ((age >= 18) && hasTicket)
{
Console.WriteLine("allowed");
}
else
{
Console.WriteLine("denied");
}
}
}
Test yourself
-
Match each operator to its meaning
- &&
- And (logical)
- ||
- Or (logical)
- !
- Not
- &
- And (bitwise)
-
n = 5; bool ok = (n > 10) && (n++ > 0); Console.WriteLine(n); what is the output?
int n = 5; bool ok = (n > 10) && (n++ > 0); Console.WriteLine(n);- 6
- 0
- True
- 5
Show answer
5 — Correct. n > 10 is false so short-circuit kicks in; n++ is not evaluated and n stays 5.
-
Write the logical AND operator
int age = 20; bool ticket = true; bool ok = (age >= 18) ____ ticket; Console.WriteLine(ok);Show answer
int age = 20; bool ticket = true; bool ok = (age >= 18) && ticket; Console.WriteLine(ok);