C++ Program to Print the 1’s Complement of Positive integer

«
»
This C++ Program which prints the 1’s complement of a positive integer. The program takes a number as the input and determines the each bit of the binary form of the number using a recursive function which is given the number as the parameter and negates it.

The function saves the remainder of the division of the number with 2, calls the same function with the quotient generated after division, the number is negated and printed after the number drops to less than equal to one and then the stack created due to recursion is unwind.

Here is source code of the C++ program which prints the 1’s complement of a positive integer. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

advertisement
  1. /*
  2.  * C++ Program to Print the 1's Complement of an Integer
  3.  */
  4.  
  5. #include<iostream>
  6. using namespace std;
  7.  
  8. void onescomp(int num)
  9. {
  10.     int rem;
  11.  
  12.     if (num <= 1)
  13.     {
  14.         cout << !num;
  15.         return;
  16.     }
  17.     rem = num % 2;
  18.     onescomp(num / 2);
  19.     cout << !rem;
  20. }
  21.  
  22. int main()
  23. {
  24.     int dec, bin;
  25.     cout << "Enter the number : ";
  26.     cin >> dec;
  27.  
  28.     if (dec < 0)
  29.         cout << dec << " is not a positive integer." << endl;
  30.     else
  31.     {
  32.         cout << "The ones complement form of " << dec << " is ";
  33.         onescomp(dec);
  34.         cout << endl;
  35.     }
  36.     return 0;
  37. }

$ g++ main.cpp
$ ./a.out
Enter the number : 10
The ones complement form of 10 is 0101

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn