fixed algorithm so that it functions correctly, attempted to add control statement to terminate the program correctly with the right output