Generating Truth Tables

1-minute read
Table of Contents

We can use C’s built-in logical operators for NOT, OR and AND in order to generate truth tables for compound logical statements. An implication is logically equivalent to taking the negation of the first proposition (the hypothesis/antecedent) OR the second (the consequent/conclusion/result):

$$p\implies q\equiv \neg p\lor q$$

Two propositions are logically equivalent when their respective truth values are always the same.

We can thus write functions to return the result of each logical operation:

#include <stdio.h>

// not p
int not(int p){
    return !p;
}

// p or q
int or(int p,int q){
    return p||q;
}

// p and q
int and(int p,int q){
    return p&&q;
}

// p implies q
int implies(int p,int q){
    return !p||q;
}

int main(){
    printf("p\tq\tnot p\tnot q\tp or q\tp and q\tp->q\tp->~q");
    printf("\n----------------------------------------------------------------\n");
    for (int n=0;n<4;n++){
        int p = (n>>1)&1;
        int q = n&1;
        printf("%d\t%d\t",p,q);
        printf("%d\t",not(p));
        printf("%d\t",not(q));
        printf("%d\t",or(p,q));
        printf("%d\t",and(p,q));
        printf("%d\t",implies(p,q));
        printf("%d",implies(p,not(q)));
        printf("\n");
    }
    return 0;
}
truth-tables.c
Copy

Challenge

Modify the code above to display the following compound propositions:

  • $\neg p \land \neg q$
  • $\neg p \implies \neg q$ (inverse)
  • $q \implies p$ (converse)
  • $\neg q \implies \neg p$ (contrapositive)

Modify the code to cater for 3 inputs (e.g. p, q and r).


Support us via BuyMeACoffee