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.
* C++ Program to Print the 1's Complement of an Integer
using namespace std;
void onescomp(int num)
if (num <= 1)
cout << !num;
rem = num % 2;
onescomp(num / 2);
cout << !rem;
int dec, bin;
cout << "Enter the number : ";
cin >> dec;
if (dec < 0)
cout << dec << " is not a positive integer." << endl;
cout << "The ones complement form of " << dec << " is ";
cout << endl;
$ 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.
If you liked this C++ Program, kindly share, recommend or like below!