Change multiple for loops to a single for loop

This change actually reduces efficiency because the calculations
for next element are done all the time; but improves code readability.
Convert nested for loops to a single for loop