Truth Table generation in C

I’m a beginner in C

I want to generate test cases(i.e. 1 and 0.) for truth table in C

If user enters

Number=3

then 2^3=8.

It generates 8 test cases in the form

0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1

Kindly Assist

So start off with n = 0. Now you need to learn about bitwise operations. Basically, << and >> operators are used to shift bits. So, n<<0 would mean nothing. n<<1 would mean shifting all the bits (in the binary representation of n) to the left side and add ‘0’ as the last bit. Obviously, n<<1 will give 2*n. Now if n = 0 then its binary representation is 000 (in 3 bits). How can you know which bit is which one? For this, do the following: (n<<0)&1. This means that do the ‘AND’ operation (read here) for 1 and n<<0. If n = 0 then:

n(0) = 000 (Bitwise operations automatically convert decimal to binary)

n<<0 = 000 (Shit bits by zero)

1 = 001 (Binary representation of 1)

(n<<0)&1= 000

This will give 0. Means that the least significant bit is ‘0’. SO print zero. Similarily check for n<<1 and n<<2. For n=0, you will get 0 for these too.

Now if n=1, i.e. 001

n<<0 = 001

1 = 001

‘&’ of these = 001

It means, that if (n<<m)&1 gives a non zero number, then the mth bit of n is set i.e. 1. Just do this upto n=0 to n=7 :slight_smile:

Bitwise operations are also explained here: http://www.codechef.com/wiki/tutorial-paying

1 Like