lab12
lab12

Reputation: 6448

Check if Integer is Positive or Negative - Objective C

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

Upvotes: 10

Views: 33372

Answers (4)

Sourabh Kumbhar
Sourabh Kumbhar

Reputation: 1054

In Swift

var value = 5
if value.signum() == 1 {
   print("Positive value")
} else if value.signum() == -1 {
   print("Negative value")
} else if value.signum() == 0 {
   print("Zero value")
}

Upvotes: 2

Paul R
Paul R

Reputation: 212949

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
}

Upvotes: 38

Eiko
Eiko

Reputation: 25632

-(void) tellTheSign:(int)aNumber
{
   printf("The number is zero!\n");
   int test = 1/aNumber;
   printf("No wait... it is positive!\n");
   int test2 = 1/(aNumber - abs(aNumber));
   printf("Sorry again, it is negative!\n");
}

;-)

Seriously though, just use

if (x < 0) {
// ...
} else if (x == 0) {
// ...
} else {
// ...
}

Don't overdo methods ans properties and helper functions for trivial things.

Upvotes: 3

Steve Sheldon
Steve Sheldon

Reputation: 6611

Maybe I am missing something and I don't understand the quesiton but isn't this just

if(value >= 0)
{
}
else
{
}

Upvotes: 3

Related Questions