 # C Programming Code Examples

## C > For Loops and While Loops Code Examples

### C program to find twos complement of a binary number

``` C program to find twos complement of a binary number Write a C program to input binary number from user and find twos complement of the binary number. How to find 2s complement of a binary number in C. Logic to find twos complement of a binary number in C programming. What is twos complement? Twos complement of an N-bit number is defined as the complement with respect to 2N. It is the result of subtracting the number from 2N, which in binary is one followed by N zeroes. In simple words twos complement is defined as sum of ones complement of a binary number and 1. 01101110 original 10010001 1's complement 10010010 2's complement Logic to find twos complement Input a binary string from user. Store it in a variable say binary. Find ones complement of the binary string. Store the result in some variable say onesComp. Declare and initialize another binary string variable to store twos complement, say twosComp = "". Initialize a variable to store carry bit during addition, say carry = 1. You may think now, why initialize carry to 1, why not 0? Since, we need to add only 1 to the binary string hence, I have initially assumed carry bit as the bit to be added. Run a loop from length of binary string to 1, decrement 1 in each iteration. The loop structure should look like for(j=SIZE-1; j>=1; j--) (where SIZE is length of the binary string). You may think, why iterating in reverse order? Because addition is carried out in right to left order. Inside the loop there can be three cases. If both current binary bit and carry bit are 1 then, put 0 to twos complement. Which is if(onesComp[j]=='1' && carry==1) then, twosComp[j] = '0', carry is still preserved to 1. If current binary bit is 0 and carry bit is 1 then, put 1 to twos complement and set carry bit to 0. Which is if(onesComp[j]=='0' && carry==1) then, twosComp[j] = '1' and carry = 0. If carry bit is 0, then assign the value of onesComp to twosComp. #include <stdio.h> #define SIZE 8 int main() { char binary[SIZE + 1], onesComp[SIZE + 1], twosComp[SIZE + 1]; int j, carry=1; printf("Enter %d bit binary value: ", SIZE); /* Input 8-bit binary string */ gets(binary); /* Find ones complement of the binary number */ for(j=0; j<SIZE; j++) { if(binary[j] == '1') { onesComp[j] = '0'; } else if(binary[j] == '0') { onesComp[j] = '1'; } } onesComp[SIZE] = '\0'; /* Add 1 to the ones complement */ for(j=SIZE-1; j>=0; j--) { if(onesComp[j] == '1' && carry == 1) { twosComp[j] = '0'; } else if(onesComp[j] == '0' && carry == 1) { twosComp[j] = '1'; carry = 0; } else { twosComp[j] = onesComp[j]; } } twosComp[SIZE] = '\0'; printf("Original binary = %s\n", binary); printf("Ones complement = %s\n", onesComp); printf("Twos complement = %s\n", twosComp); return 0; } ``` 