Learn Objective-C: Integer Operations
Extensions provide a more in-depth overview of various topics. Here, I present a more in-depth discussion behind primitive data types.
Type int
As mentioned before, integers consist of individual digits. You can prefix it with a minus sign (a hyphen) to make it negative. You cannot put spaces, commas, or periods inside ints.
When dividing an integer by another, integer division occurs. In this case, the remainder of the division is dropped. Therefore, the result of 8/5 is 1, not 1.6. A practical use of this is as follows:
int number = 1234;
int thousands = number / 1000;
NSLog("@The thousands place of %d is %d.", number, thousands);
The output of the code above is:
The thousands place of 1234 is 1.
In contrast, the modulus operator (%
) is used to derive the exact remainder of integer division. Therefore, 8 % 5 = 3
.
Extending the above example:
int number = 1234;
int thousands = number / 1000;
NSLog("@The thousands place of %d is %d.", number, thousands);
int hundreds = (number % 1000) / 100;
NSLog("@The hundreds place of %d is %d.", number, hundreds);
int tens = ((number % 1000) % 100) / 10;
NSLog(@"The tens place of %d is %d.", number, tens);
int ones = (((number % 1000) % 100) % 10);
NSLog(@"The ones place of %d is %d.", number, ones);
The output of the code is:
The thousands place of 1234 is 1.
The hundreds place of 1234 is 2.
The tens place of 1234 is 3.
The ones place of 1234 is 4.
The code above is rather involved, but try to figure it out. Remember, the modulus operator extracts the remainder of the division that could have been placed in its place.
This post is part of the Learn Objective-C in 24 Days course.