Pages - Menu

Monday 8 October 2012

Printing the truth table for the logical operators in C#

The program below prints a table containing the results of the four basic logical operations: AND, OR, XOR and NOT. The logical operators supporting those operations are: &, |, ^, !.
The operands of a logical operation must be of type bool and the result is, as well, of type bool. The bool type represents true/false values. 
using System;

class TruthTable
{
    static void Main()
    {
        bool p, q;
        Console.WriteLine("_____________________________________________");
        Console.WriteLine("\n  P \tQ\tAND\tOR\tXOR\tNOT");
        Console.WriteLine("_____________________________________________");
        p = true; q = true;
        Console.WriteLine("  "+p+"\t"+q+"\t"+(p&q)+"\t"+(p|q)+"\t"+(p^q)+"\t"+(!p));
        Console.WriteLine("_____________________________________________");
        p = true; q = false;
        Console.WriteLine("  "+p+"\t"+q+"\t"+(p&q)+"\t"+(p|q)+"\t"+(p^q)+"\t"+(!p));
        Console.WriteLine("_____________________________________________");
        p = false; q = true;
        Console.WriteLine("  "+p+"\t"+q+"\t"+(p&q)+"\t"+(p|q)+"\t"+(p^q)+"\t"+(!p));
        Console.WriteLine("_____________________________________________");
        p = false; q = false;
        Console.WriteLine("  "+p+"\t"+q+"\t"+(p&q)+"\t"+(p|q)+"\t"+(p^q)+"\t"+(!p));
        Console.WriteLine("_____________________________________________");
        Console.Read();
    }
}

Output:

No comments:

Post a Comment