Check if Integer is Positive or Negative - Objective C

lab12 picture lab12 · Jun 17, 2010 · Viewed 31.6k times · Source

How can I tell in objective-c coding if an integer is positive or negative. I'm doing this so that I can write an "if" statement stating that if this integer is positive then do this, and if its negative do this.

Thanks,

Kevin

Answer

Paul R picture Paul R · Jun 17, 2010
if (x >= 0)
{
    // do positive stuff
}
else
{
    // do negative stuff
}

If you want to treat the x == 0 case separately (since 0 is neither positive nor negative), then you can do it like this:

if (x > 0)
{
    // do positive stuff
}
else if (x == 0)
{
    // do zero stuff
}
else
{
    // do negative stuff
}