Truth Table of AND OR NOT in Kotlin

A truth table is a table that lists all possible combinations of input values for a logical expression and their corresponding output values. It is used to determine the truth value of a logical expression for all possible combinations of its variables.

A truth table typically consists of a row for each possible combination of input values, and columns that show the input values and the resulting output value. The output value is usually represented by the Boolean values “true” or “false”.

For example, consider the logical expression “A AND B”, where A and B are Boolean variables. The truth table for this expression would be:

A

0
0
1
1
B

0
1
0
1
A AND B
———–
0
0
0
1

In this truth table, there are four possible combinations of input values for A and B, and the output value for each combination is calculated using the logical operator AND. The resulting truth table shows the output value for each combination of input values.

Truth tables are commonly used in logic, mathematics, and computer science to evaluate logical expressions, to design and analyze digital circuits, and to test the correctness of computer programs.

Kotlin
fun main() {
    val truthValues = listOf(true, false)
    println("Truth table for AND operator:")
    println("|  A   |  B   |  A AND B  |")
    for (a in truthValues) {
        for (b in truthValues) {
            val result = a && b
            println("| $a | $b |   $result    |")
        }
    }
    println()
    println("Truth table for OR operator:")
    println("|  A   |  B   |  A OR B  |")
    for (a in truthValues) {
        for (b in truthValues) {
            val result = a || b
            println("| $a | $b |   $result   |")
        }
    }
    println()
    println("Truth table for NOT operator:")
    println("|   A  |   NOT A  |")
    for (a in truthValues) {
        val result = !a
        println("| $a |   $result  |")
    }
}

This code defines a list of Boolean values truthValues that contains true and false. It then generates truth tables for the logical operators AND, OR, and NOT using nested loops to iterate over all possible combinations of input values.

The output shows the truth tables for each logical operator in a tabular format, with columns for the input values and the resulting output value.

Leave a Comment