Infosys interview question

Write the program for the given problem