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:

  1. int number = 1234;
  2. int thousands = number / 1000;
  3. 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:

  1. int number = 1234;
  2. int thousands = number / 1000;
  3. NSLog ("@The thousands place of %d is %d.", number, thousands);
  4. int hundreds = (number % 1000) / 100;
  5. NSLog ("@The hundreds place of %d is %d.", number, hundreds);
  6. int tens = ((number % 1000) % 100) / 10;
  7. NSLog (@"The tens place of %d is %d.", number, tens);
  8. int ones = (((number % 1000) % 100) % 10);
  9. NSLog (@"The ones place of %d is %d.", number, ones);

The output of the code is:

  1. The thousands place of 1234 is 1.
  2. The hundreds place of 1234 is 2.
  3. The tens place of 1234 is 3.
  4. 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.

Author: Feifan Zhou