To test whether a number is negative

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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: