Move p and q at the end of the loop