I have been trying to check whether an NSInteger is odd or even. I have found a way to do it using C but it doesn't work with Objective-C. How would I do this?
If a number is evenly divisible by 2 with no remainder, then it is even. You can calculate the remainder with the modulo operator % like this num % 2 == 0 . If a number divided by 2 leaves a remainder of 1, then the number is odd. You can check for this using num % 2 == 1 .
A number is even if, when divided by two, the remainder is 0. A number is odd if, when divided by 2, the remainder is 1.
The required code is provided below. num = int (input (“Enter any number to test whether it is odd or even: “) if (num % 2) == 0: print (“The number is even”) else: print (“The provided number is odd”) Output: Enter any number to test whether it is odd or even: 887 887 is odd.
Using Modulo Operator ( % ) This is the most used method to check whether the given number is even or odd in practice. Modulo operator is used to get the remainder of a division. For example, 5 % 2 returns 1, i.e., the remainder when divided 5 by 2.
NSInteger
is defined as int
(or long
on some environments). So checking on oddity is like for plain int:
NSInteger num;
if (num % 2)
// odd
else
// even
NSInteger n = 5;
NSLog(@"%s", n & 1 ? "odd" : "even");
or using if
if (n & 1) {
; // odd
} else {
; // even
}
with some output:
if (n & 1) {
NSLog(@"odd");
} else {
NSLog(@"even");
}
the pointer example:
NSInteger x = 7;
NSInteger *y = &x;
if (*y & 1) {
NSLog(@"odd");
} else {
NSLog(@"even");
}
As far as I'm aware. NSInteger
, unlike NSNumber
, is just a typeder to a real integer type along the lines of:
typedef long NSInteger;
So you should be able to do:
NSInteger nsintvar = 77;
if ((nsintvar % 2) == 0) {
// number is even
} else {
// number is odd
}
Here's a complete program, compiled under Cygwin with GNUstep, which illustrates it:
#import <stdio.h>
#import <Foundation/NSObject.h>
int main( int argc, const char *argv[] ) {
NSInteger num;
for (num = 0; num < 20; num++) {
if ((num % 2) == 0) {
printf ("%d is even\n", num);
} else {
printf ("%d is odd\n", num);
}
}
return 0;
}
It outputs:
0 is even
1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd
10 is even
11 is odd
12 is even
13 is odd
14 is even
15 is odd
16 is even
17 is odd
18 is even
19 is odd
Those other answers should work. Maybe it's a problem with your makefile or something. Think outside that piece of code.
If all else fails just declare the integer as an int. You don't have to declare it as NSInteger.
Use the "%" operator. Essentially, it works out the remainder when you divide a number. So:
number % 2
Would be = 0 if number was even, as an even number divided by 2 has no remainders. If it does not = 0, it must be odd.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With