while (flag=true)
That just makes flag true every iteration, you mean while(flag==true) which honestly can just be while(flag)