Lesson 7 of 15
Truth Table Generator
Truth Table Generator
A truth table lists all possible input combinations and the corresponding output. For n inputs, there are 2^n rows.
For a 2-input function, the rows are:
A B | output
0 0 | ?
0 1 | ?
1 0 | ?
1 1 | ?
To generate all combinations programmatically, iterate i from 0 to 2^n - 1, and extract each input bit with a right-shift and mask:
// For n=2, i=3 (binary: 11):
// input 0 (MSB) = (3 >> 1) & 1 = 1
// input 1 (LSB) = (3 >> 0) & 1 = 1
Your Task
Implement truthTable(fn, n) where:
fnis a function that takesnbit arguments (0 or 1)nis the number of inputs
Return an array of arrays. Each inner array contains the n inputs followed by the output.
Then generate and print the truth table for XOR (2 inputs), printing each row as "A B => out".
JavaScript loading...
Loading...
Click "Run" to execute your code.