Your program takes as input a 3-variable Boolean function in the form of a sum-of-products. For example, the input can look like "AB" + "AB'C" + "A'B'C'". The double quotations are needed so that the ' is taken as a regular character, negating the preceding variable, and not considered a special character.
• The evaluation of each term, e.g., AB'C, is done in a separate function, called, evalTerm(int A, int B, int C, char *term) that returns the Boolean value (0 or 1) of the corresponding term.
• Your program should print the Boolean function followed by its truth table.
#include
#include
// Function to evaluate a single term
int evalTerm(int A, int B, int C, char *term) {
int result = 1;
for (int i = 0; i < strlen(term); i++) {
if (term[i] == 'A' && !A) {
result = 0;
break;
} else if (term[i] == 'B' && !B) {
result = 0;
break;
} else if (term[i] == 'C' && !C) {
result = 0;
break;
}
}
return result;
}
// Function to print the truth table
void printTruthTable(char *function) {
int A, B, C;
printf("Truth table of F %s
", function);
printf("A B C | F
");
printf("------|---
");
for (A = 0; A <= 1; A++) {
for (B = 0; B <= 1; B++) {
for (C = 0; C <= 1; C++) {
int result = 0;
int numTerms = 0; // Count the number of terms
char *term = strtok(function, "+");
while (term != NULL) {
result += evalTerm(A, B, C, term);
numTerms++; // Increment the term count
term = strtok(NULL, "+");
}
printf("%d %d %d | %d
", A, B, C, result == numTerms ? 1 : 0);
}
}
}
}
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("Truth table generator for 3-variable Boolean functions %s
", argv[0]);
printf("Usage: Enter a Boolean function as a sum of products %s
", argv[0]);
return 1;
}
printTruthTable(argv[1]);
return 0;
}
Test runs:
$ truthTableGenerator //call without arguments
$ Truth table generator for 3-variable Boolean functions
$ Usage: enter a Boolean function as a sum of products
$ E.g.: ./a.out AB + BC+ABC"
F is the sum of 4 product terms F = AB' + BC + ABC + ABC
Truth table of F ABC|F
000 001 010 011 100 101 110
1 0 1 0 1 1 1
1