This program is to find whether two numbers are of opposite sign. We will be using two approach to solve this:

**First approach:**

Simple Xor both the numbers and if result is less than 1 means the given two numbers are of opposite sign

```
#include <stdio.h>
int main()
{
int num1, num2;
printf("\n Enter the first number : ");
scanf("%d",&num1);
printf("\n Enter the second number :");
scanf("%d",&num2);
if ((num1 ^ num2) <1)
printf("\n The given numbers have opp sign\n");
else
printf("\n The given numbers do not have opp sign\n");
return 0;
}
```

**Output:**

```
Enter the first number : 9
Enter the second number :8
The given numbers do not have opp sign
```

**Second Approach:**

Get the MSB bit of each number and Xor them, if the result is 1 means they are of opposite sign

```
#include <stdio.h>
int get_msb_bit(int num)
{
int no_of_bits = sizeof(num) *8;
if ((num >> no_of_bits -1) &1)
return 1;
else
return 0;
}
int main()
{
int num1, num2;
printf("\n Enter the first number : ");
scanf("%d",&num1);
printf("\n Enter the second number :");
scanf("%d",&num2);
int res1 = get_msb_bit(num1);
int res2 = get_msb_bit(num2);
if (res1 ^res2)
printf("\n The two numbers are of opposite sign");
else
printf("\n The two numbers are of same sign");
return 0;
}
```

**Output:**

```
Enter the first number : 9
Enter the second number :-1
The two numbers are of opposite sign
```

**The first approach is better than second**.

Categories: C Language

## Leave a Reply