changed two for-loops to use an already defined variable