if (K==0)
should probably be
if (k==0)
Just a typo...
It is easy to localize this problem - you know where you want to terminate your loop and the only thing which can go wrong is your if
statement. Spotting such things is easy and one of the most basic things to master in programming. You need to learn debugging as soon as your programs start to be longer than 5 lines.