Adding a html class based on post count

If I understood this issue correctly the problem with your current code is that you are incrementing $totalPosts variable inside the while loop, so the variable gets incremented after every post thus resulting in the running order you described.

To get the amount of posts returned matching the query, use $loop->found_posts (in this case)

More information, examples and documentation about the WP_Querycan be found from WordPress Codex