armedunity.com uses cookies to improve user experience.

By continuing to use this site, you agree to allow us to store cookies on your computer.

• 0

## Question

Hello, a bit over an hour ago, I signed up on codefights, and I got to a thing where you have to get the century from year. Which was pretty easy, and there's soo many ways to do it.

Anyway, after I came up with a solution, I wanted to see how other people solved it, and the most interesting one I saw were

How does this work?

I know

--------------------------------

year = 1800

year / 100 + 1 = 19

expected = 18

--------------------------------

year = 1801

year / 100 + 1 = 19

expected = 19

--------------------------------

but if I add the -- before year, then it will output

--------------------------------

year = 1800

--year / 100 + 1 = 18

expected = 18

--------------------------------

year = 1824

--year / 100 + 1 = 19

expected = 19

--------------------------------

How come after -- has been added before year, it all gets decremented kind of like,

if year % 100 == 0 then decrement year / 100 + 1.

Am I completely off? This just confuses me a bit, and it just makes me nuts, not knowing how it works

I have seen it in for loops too(Not often though, only seen it being used in for loops 2 times), like so

I have seen it with ++i too

## Recommended Posts

• 1

--i means decrement before using i. i-- means decrement after using i. Example:

//i = 0, only add at the next iteration

for(i = 0; i < 10; i++)

//I will start incrementing after 0 for a total of 10 iterations

//i = 0, increment right away so it now = 1

for(i = 0; i < 10; ++i)

//I will start incrementing now for a total of 9 iterations

the only reason i++ is seen more often is because lists and arrays start at 0. So if you use ++i in a loop trying to loop an array, you'd completely skip over 0. But if you've ever built an engine you'd use ++i to pass data to the graphics via OpenGL or dx which start at 1.

There is other scenarios where you could use ++i vs i++ but try and keep it simple, use one or the other. Example:

for(i = 1; i < 10; i++)

is the same as:

for(i = 0; i < 10; ++i)

so just stick to one and you'll be good 👍

##### Share on other sites

• 0

Thanks, makes completely sense now

## Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

×   Pasted as rich text.   Paste as plain text instead

Only 75 emoji are allowed.