Answer:
Following are attached images that will help you understand the complete code. The code is tested with different variables and different outputs are obtained. All the necessary description is given in the form o comments inside the code.
Explanation: