# Extension 1: 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.

1. #### Ethan

/  October 17, 2010

Good tutorial so far. I have never really understood a practical use of the modulus operator. So simple!!!! Thanks! Keep going!
-Ethan

• #### inspire48

/  October 17, 2010

You’re welcome! Thanks for stopping by. I have a lot more stuff to put, I just need to find time.

• #### inspire48

/  October 19, 2010

Another practical use of the modulus operatorâ€”to limit the results of an operation:

https://cupsofcocoa.wordpress.com/2010/10/19/extension-3-a-b-c/

• #### jeff

/  August 10, 2012

another common use is to determine if number is even or odd:
for(int i=0;i<10;i++){
NSLog(@"%d is %s", i, (i % 2==0 ? "even" : "odd"));
}

This example also uses the ternary operator, which is short-hand for an if/else.

• ## Welcome

My goal is to make CupsOfCocoa into a beautiful source for beginners to the iPhone platform to get started. Subscribe below for more, and stay tuned!

• ## Contact Me

If you need to contact me for any reason, feel free to send me an email.
• ## The Giving Spirit

If you've found this site helpful, would you consider donating a little sum? Any amount is appreciated...Thanks so much!