if
will only check the value of k once,
while
will continue(like a loop) what in the scope till your condition is false
you can use while
if you are waiting for a specific action to stop/break, and if
when need to check something at a time.
I hope that was clear.
in your case for
will works well.
CLICK HERE to find out more related problems solutions.