I have understood the concept but unable to write the code

please share the code as i am unable to write the code

see this: