This problem is to find whether a given number is negative or not
The logic behind solving this problem is to get the MSB bit of a number and if its set means the given number is negative as MSB bit of negative number is always set.
#include <stdio.h>
int find_is_negative(int num)
{
int no_of_bits = sizeof(num) *8;
//if ( num & 1UL << no_of_bits -1) This also works
if ((num >> no_of_bits -1) &1)
return 1;
else
return 0;
}
int main()
{
int num;
printf("\n Enter the number: ");
scanf("%u", &num);
if(find_is_negative(num))
printf("\n The given number is negative");
else
printf("\n The given number is not negative");
return 0;
}
Output:
Enter the number: -9
The given number is negative
Categories: C Language
Leave a Reply