Logical operators in C# are used to combine multiple conditions in expressions, particularly in decision-making statements like if, while, and for.
They allow you to create complex conditions by evaluating multiple conditions at once. The main logical operators are:
- AND (&&)
- OR (||)
- NOT (!)
This tutorial will cover each operator with examples, including:
1. Overview of Logical Operators
Here’s a quick rundown of the logical operators:
Operator | Description | Example |
---|---|---|
&& | Logical AND: true if both conditions are true | a && b |
` | ` | |
! | Logical NOT: inverts the condition | !a |
Logical operators are usually combined with relational operators to form complex conditional expressions.
2. Using Logical Operators with if Statements
Logical operators are typically used in if statements to evaluate multiple conditions simultaneously.
Example: AND (&&) Operator
The && (AND) operator checks if both conditions are true. If either condition is false, the result is false.
using System; public class AndOperatorExample { public static void Main() { int age = 20; bool hasLicense = true; if (age >= 18 && hasLicense) { Console.WriteLine("You are eligible to drive."); } else { Console.WriteLine("You are not eligible to drive."); } } }
In this example:
- The if statement checks that both conditions (age >= 18 and hasLicense) are true.
- Since both are true, it prints “You are eligible to drive.”
Example: OR (||) Operator
The || (OR) operator checks if at least one condition is true. If both conditions are false, then the result is false.
using System; public class OrOperatorExample { public static void Main() { double grade = 75; int extraCreditProjects = 3; if (grade >= 80 || extraCreditProjects >= 2) { Console.WriteLine("You qualify for a bonus."); } else { Console.WriteLine("You do not qualify for a bonus."); } } }
In this example:
- The if statement checks if either the grade is 80 or higher or the student has completed at least 2 extra-credit projects.
- Since extraCreditProjects is 3, the condition is true, so it prints “You qualify for a bonus.”
Example: NOT (!) Operator
The ! (NOT) operator inverts the condition. If the condition is true, ! changes it to false, and vice versa.
using System; public class NotOperatorExample { public static void Main() { bool isWeekend = false; if (!isWeekend) { Console.WriteLine("It's a weekday, time to work!"); } else { Console.WriteLine("It's the weekend, time to relax!"); } } }
In this example:
- !isWeekend inverts the isWeekend value.
- Since isWeekend is false, !isWeekend becomes true, and the output is “It's a weekday, time to work!”
3. Combining Multiple Logical Operators
Logical operators can be combined to create complex conditions.
Example: Checking Age and Citizenship
using System; public class ComplexConditionExample { public static void Main() { int age = 20; bool isCitizen = true; bool hasVoterID = true; if ((age >= 18 && isCitizen) || hasVoterID) { Console.WriteLine("You are eligible to vote."); } else { Console.WriteLine("You are not eligible to vote."); } } }
In this example:
- The condition (age >= 18 && isCitizen) || hasVoterID checks if the person is a citizen and at least 18 years old or if they have a voter ID.
- Since both age >= 18 && isCitizen is true, it outputs “You are eligible to vote.”
4. Logical Operators with Loops
Logical operators are often used in loops to control when the loop should continue or break.
Example: Validating User Input with while and ||
using System; public class WhileLoopExample { public static void Main() { string input; do { Console.Write("Enter 'yes' or 'no': "); input = Console.ReadLine().ToLower(); } while (input != "yes" && input != "no"); Console.WriteLine("You entered: " + input); } }
In this example:
- The while loop continues as long as input is neither “yes” nor “no”.
- The && operator requires both conditions (input != “yes” and input != “no”) to be true for the loop to continue.
Example: Counting with OR Condition
using System; public class OrInLoopExample { public static void Main() { int count = 1; while (count <= 10) { if (count % 2 == 0 || count % 3 == 0) { Console.WriteLine("Count: " + count); } count++; } } }
In this example:
- The loop prints the count only if count is divisible by 2 or 3.
- Using || makes the condition true if count is divisible by either number.
5. Practical Examples
Example 1: Admission Eligibility
using System; public class AdmissionEligibility { public static void Main() { double gpa = 3.6; int extracurriculars = 4; if (gpa >= 3.5 && extracurriculars >= 3) { Console.WriteLine("Eligible for admission."); } else { Console.WriteLine("Not eligible for admission."); } } }
In this example:
- Both conditions (gpa >= 3.5 and extracurriculars >= 3) must be true for admission eligibility.
Example 2: Check for Discount Eligibility
using System; public class DiscountEligibility { public static void Main() { bool isStudent = true; bool isSenior = false; bool isVeteran = true; if (isStudent || isSenior || isVeteran) { Console.WriteLine("Eligible for a discount."); } else { Console.WriteLine("Not eligible for a discount."); } } }
In this example:
- The program checks if a person is eligible for a discount by checking if they meet any of the three conditions (isStudent, isSenior, or isVeteran).
- Since isStudent is true, it prints “Eligible for a discount.”
Example 3: Verifying Conditions with ! Operator
using System; public class LoginVerification { public static void Main() { bool isUsernameCorrect = true; bool isPasswordCorrect = false; if (!isUsernameCorrect || !isPasswordCorrect) { Console.WriteLine("Login failed. Please check your credentials."); } else { Console.WriteLine("Login successful."); } } }
In this example:
- The condition checks if either isUsernameCorrect or isPasswordCorrect is false.
- If either is incorrect, it prints “Login failed.”
Summary
Logical operators are essential for making complex conditions in C#. Here’s a recap of the main points:
- AND (&&): Returns true only if both conditions are true.
- OR (||): Returns true if at least one condition is true.
- NOT (!): Inverts the condition; true becomes false and vice versa.
- Combining Logical Operators: You can use multiple logical operators to create complex conditions.
- Practical Use: Logical operators are commonly used in if statements and loops to control program flow.