rewritten using looping and counters