I am not able to understand beyond this and how to apply concept of pattern

Please check this code with comments and dry run it yourself you will get it https://ide.codingblocks.com/s/30137