Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

what is a remainder operator??

please help, i need to know what this is

Richard Hanolt
Richard Hanolt
3,726 Points

% is the remainder operator

so if 10 / 2 = 5 the remainder operator basically does the same thing but it returns the remainder instead of the actual answer ex. 10 % 2 = 0 or 10 % 3 = 1

1 Answer

It gives you the remainder of two numbers. For example: 10 % 2 = 0 So 10 divided by 2 is 5 with a remainder of zero. You could use this to select only even or odd numbers of a range using bool for example.

Throw this into a playground to see what I mean. Since I entered 100 as the Int when I called the function it prints "Even".

func oddOrEven(n: Int) -> String { if n % 2 == 0 { print("Even") } else { print("Odd") } return "((n))" }

oddOrEven(100)