changed loops to pre-increment