What is Logical operators With Example Code

Logical operators in C# are used to perform logical operations on boolean values. These operators include AND (&&), OR (||), and NOT (!). Here's a program demonstrating logical operators:



using System;
 
class Program
{
    static void Main(string[] args)
    {
        bool condition1 = true;
        bool condition2 = false;
 
        // Logical AND (&&): Returns true if both conditions are true.
        bool resultAND = condition1 && condition2;
        Console.WriteLine($"Logical AND: {condition1} && {condition2} = {resultAND}");
 
        // Logical OR (||): Returns true if at least one of the conditions is true.
        bool resultOR = condition1 || condition2;
        Console.WriteLine($"Logical OR: {condition1} || {condition2} = {resultOR}");
 
        // Logical NOT (!): Inverts the boolean value of a condition.
        bool resultNOT1 = !condition1;
        bool resultNOT2 = !condition2;
        Console.WriteLine($"Logical NOT: !{condition1} = {resultNOT1}, !{condition2} = {resultNOT2}");
    }
}


//Result
//Logical AND: True && False = False
//Logical OR: True || False = True
//Logical NOT: !True = False, !False = True


using System;
 
class Program
{
    static void Main(string[] args)
    {
        int x = 10;
        int y = 5;
        int z = 0;
 
        // Logical AND (&&): Returns true if both conditions are true.
        bool logicalAND = (x > y) && (y > z);
        Console.WriteLine($"Logical AND: {logicalAND}");
 
        // Logical OR (||): Returns true if at least one of the conditions is true.
        bool logicalOR = (x > y) || (y == z);
        Console.WriteLine($"Logical OR: {logicalOR}");
 
        // Conditional operator (?:): Evaluates a condition and returns one of two values based on the result.
        string result = (x > y) ? "x is greater than y" : "x is less than or equal to y";
        Console.WriteLine($"Conditional Operator: {result}");
    }
}



//Logical AND: True
//Logical OR: True
//Conditional Operator: x is greater than y