In any coder forum that I use, people usually frown upon giving others the sollution for the homework given to a student, but I will give a clue: It can be done iteratively or recursively. Here is the code:
I hate lazy people
I hate lazy people