Q:

C program to find positive or negative using bitwise operators and if-else

belongs to collection: C Programming on Numbers

0

This program asks the user to enter any number. Next, this c program checks whether the given value is positive or negative or zero using the if-else statement.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

#include <stdio.h>
// Total bits required to represent integer
#define BITS sizeof(int) * 8
//Logic to check whether a number is positive
int isPositive(int n)
{
    return (!( n & (1 << (BITS -1 )) | (!n)));
}
int main()
{
    int num,numType;
    printf("Enter any number: ");
    scanf("%d", &num);
    numType = isPositive(num);
    if(numType && num)
    {
        printf("Positive number\n");
    }
    else if (num)
    {
        printf("Negative number\n");
    }
    else
    {
        printf("Zero\n");
    }
    return 0;
}

 

Output:

Enter any number: -10
Negative number

Enter any number: 10
Positive number

Enter any number: 0
Zero

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C Programming on Numbers

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C program to find the negative or positive number ... >>
<< C program to check positive or negative without us...