C Programming Code Examples C > For Loops and While Loops Code Examples C program to find ones complement of a binary number C program to find ones complement of a binary number Write a C program to input binary number from user and find ones complement of binary number using loop. How to find 1s complement of a binary number in C programming. What is Ones complement? Ones complement of a binary number is defined as value obtained by inverting all binary bits. It is the result of swapping all 1s to 0s and all 0s to 1s. 01101110 >> 10010001 Logic to find ones complement of a number Input a binary string from user. Store it in a variable say binary. Run a loop from 1 to length of binary string, increment 1 in each iteration. The loop structure should look like for(j=0; j<SIZE; j++) (where SIZE is the length of binary digit). Inside loop there are two possibilities - Print 0 for each 1 binary bit i.e. if(binary[j] == '1'). Print 1 for each 0 binary bit i.e. if(binary[j] == '0'). #include <stdio.h> #define SIZE 8 int main() { char binary[SIZE + 1], onesComp[SIZE + 1]; int j, error=0; printf("Enter %d bit binary value: ", SIZE); /* Input binary string from user */ gets(binary); /* Store all inverted bits of binary value to onesComp */ for(j=0; j<SIZE; j++) { if(binary[j] == '1') { onesComp[j] = '0'; } else if(binary[j] == '0') { onesComp[j] = '1'; } else { printf("Invalid Input"); error = 1; /* Exits from loop */ break; } } /* Marks the end of onesComp string */ onesComp[SIZE] = '\0'; /* Check if there are binary string contains no error */ if(error == 0) { printf("Original binary = %s\n", binary); printf("Ones complement = %s", onesComp); } return 0; }