Edited to include if{} in the nested loop, added an iteration counter.