Step wise modulus

although i know the modulus property but i am just not getting how we take the step wise modulus
like in fast modulo exponentiation https://ide.codingblocks.com/#/s/15387
how do we know in which terms do we have to apply step wise mod as in this we applied mod in both res as well as a.
ques link https://hack.codingblocks.com/contests/c/528/743

Whenever we need to find some result % MOD, we always do step-wise MOD 'cause % MOD ensures that the value doesn’t overflow. So we will do % MOD in every step which contributes to result