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.
/*
* C++ Program to Print the 1's Complement of an Integer
*/
#include<iostream>
using namespace std;
void onescomp(int num)
{
int rem;
if (num <= 1)
{
cout << !num;
return;
}
rem = num % 2;
onescomp(num / 2);
cout << !rem;
}
int main()
{
int dec, bin;
cout << "Enter the number : ";
cin >> dec;
if (dec < 0)
cout << dec << " is not a positive integer." << endl;
else
{
cout << "The ones complement form of " << dec << " is ";
onescomp(dec);
cout << endl;
}
return 0;
}
$ 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
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.
If you find any mistake above, kindly email to [email protected]Related Posts:
- Apply for Computer Science Internship
- Check Computer Science Books
- Check Programming Books
- Check C++ Books
- Practice Computer Science MCQs