6

I am super confused what the percentage sign does in Objective C. Can someone explain to me in language that an average idiot like myself can understand?! Thanks.

Aero Wang
  • 8,382
  • 14
  • 63
  • 99

4 Answers4

9

% is the modulo operator, so for example 10 % 3 would result in 1.

If you have some numbers a and b, a % b gives you just the remainder of a divided by b.

So in the example 10 % 3, 10 divided by 3 is 3 with remainder 1, so the answer is 1.

If there is no remainder to a divided by b, the answer is zero, so for example, 4 % 2 = 0.

Here's a relevant SO question about modular arithmetic.

Community
  • 1
  • 1
Charles Martin
  • 338
  • 2
  • 13
4

Same as what it does in C, it's "modulo" (also known as integer remainder).

Michael Dautermann
  • 88,797
  • 17
  • 166
  • 215
1

% is the modulo operator. It returns the remainder of <number> / <number>. For example:

5 % 2 

means 5 / 2, which equals 2 with a remainder of 1, so, 1 is the value that is returned. Here's some more examples:

3 % 3 == 0 //remainder of 3/3 is 0
6 % 3 == 0 //remainder of 6/3 is 0
5 % 3 == 2 //remainder of 5/3 is 2
15 % 4 == 3 //remainder of 15/4 is 3
99 % 30 == 9 //remainder of 99/30 is 9

The definition of modulo is:

mod·u·lo

(in number theory) with respect to or using a modulus of a specified number. Two numbers are congruent modulo a given number if they give the same remainder when divided by that number.

Community
  • 1
  • 1
Jojodmo
  • 23,357
  • 13
  • 65
  • 107
0

In Mathematics, The Percentage Sign %, Called Modulo (Or Sometimes The Remainder Operator) Is A Operator Which Will Find The Remainder Of Two Numbers x And y. Mathematically Speaking, If x/y = {(z, r) : y * z + r = x}, Where All x, y, and z Are All Integers, Then x % y = {r: ∃z: x/y = (z, r)}. So, For Example, 10 % 3 = 1.

Some Theorems And Properties About Modulo

  • If x < y, Then x % y = x
  • x % 1 = 0
  • x % x = 0
  • If n < x, Then (x + n) % x = n
  • x Is Even If And Only If x % 2 = 0
  • x Is Odd If And Only If x % 2 = 1
  • And Much More!

Now, One Might Ask: How Do We Find x % y? Well, Here's A Fairly Simple Way:

  1. Do Long Division. I Could Explain How To Do It, But Instead, Here's A Link To A Page Which Explains Long Division: https://www.mathsisfun.com/numbers/long-division-index.html

  2. Stop At Fractions. Once We Reach The Part Where We Would Normally Write The Answer As A Fraction, We Should Stop. So, For Example, 101/2 Would Be 50.5, But, As We Said, We Would Stop At The Fractions, So Our Answer Ends Up Being 50.

  3. Output What's Left As The Answer. Here's An Example: 103/3. First, Do Long Division. 103 - 90 = 13. 13 - 12 = 1. Now, As We Said, We Stop At The Fractions. So Instead Of Continuing The Process And Getting The Answer 34.3333333..., We Get 34. And Finally, We Output The Remainder, In This Case, 1.

NOTE: Some Mathematicians Write x mod y Instead Of x % y, But Most Programming Languages Only Understand %.