created recursive function as per instructions