I've got an assignment to write a program that takes a decimal, and prints it's binary format, the 1's complement of the binary format, and the 2's complement of the binary format.

So far I've come up with the following solution:

Code:

#include "stdafx.h"
#include "conio.h"
#include "math.h"
int _tmain(int argc, _TCHAR* argv[])
{
int n, k, c;
printf("Enter an integer in decimal number system\n");
scanf("%d", &n);
printf("%d in binary number system is:\n", n);
for (c = 31; c >= 0; c--)
{
k = n >> c;
if (k & 1)
printf("1");
else
printf("0");
}
printf("\n\n");
printf("%d's complement is:\n", n);
for (c = 31; c >= 0; c--)
{
k = n >> c;
if (k & 1)
printf("0");
else
printf("1");
}
_getch();
return 0;
}

This way the binary conversion is working, but it starts the number with a bunch of 0s, based on c's value. And because of this, the complement will include a bunch of 1's that are not needed. Moreover, I have absolutely no idea how it'd be possible to add +1 to the created number, so that we get the 2's complement.

Could you please help me with this, I'm sure there's a better way to start the whole process, but I could only find alternatives based on functions, and we haven't learned about those yet.

Thanks very much!