-9

Is it possible to know if a number is positive or negative or 0 in c language using only two if conditions?

If yes, then how? please let me know

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
user2753523
  • 473
  • 2
  • 8
  • 23

3 Answers3

3

Use only two ifs:

if (num <= 0) {
      if (num == 0) {
          /* num is zero */
      } else {
          /* num is negative */
      }
} else {
    /* num is positive */
}
Sangeeth Saravanaraj
  • 16,027
  • 21
  • 69
  • 98
Lee Duhem
  • 14,695
  • 3
  • 29
  • 47
3

I hope this can solve your problem

#include <stdio.h>
int main()
{
    float num;
    printf("Enter a number: ");
    scanf("%f",&num);    // Take input from user
    if (num<=0)          // if Number is >= 0
    {                    
        if (num==0)      // if number is equal to zero
          printf("You entered zero.");
        else             // if number is > 0
          printf("%.2f is negative.",num);
    }
    else                // if number is < 0
      printf("%.2f is positive.",num);
    return 0;
}
Omer Obaid
  • 416
  • 1
  • 6
  • 24
0

If c is a floating point, the problem becomes interesting.

c may be
1) > 0
2) < 0
3) = 0
4) "Not-a-Number"

#include <math.h>
...
int classification = fpclassify(x); 
if (classification == FP_NAN || classification == FP_ZERO)) {
  if (classification == FP_NAN) puts("NaN")
  else puts("zero");
}
else  {
  if (signbit(x)) puts("< 0" )
  else puts("> 0");
}

At most, 2 if()s executed.

Without using classification functions/macros

if (x != x || x == 0.0)) {
  if (x != x) puts("NaN")
  else puts("zero");
}
else  {
  if (x < 0.0) puts("< 0" )
  else puts("> 0");
}
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256