changed while codes into for loop,eliminating redundant variable i