Tuesday, April 29, 2008

Solution to Group 3 Problem

Group 3.

View the question here.

Here we want to practice a bit of recursion.
Whenever you go about writing recursive code, you have to keep two things in mind.
1. There must be a terminating condition.
2. As the number of recursions increase, the problem state should approach the terminating condition.

Lets see that with respect to this program.



Now lets come back to the 2 conditions that we discussed above.

1. There must be a terminating condition. As you see, the (if n < 10) is the terminating condition. It is a terminating condition because a number is returned if that condition is satisfied. (Unlike the default case which calls the function again)
2. As the number of recursions increase, the problem state should approach the terminating condition. This is also satisfied because, we keep dividing the number by 10 in the default condition. So the number will keep becoming smaller and smaller and finally become <10, and the terminating condition will be reached.

OK, so did you find a problem with the program above?
Yes? -> Great!
No? -> If you check the previous post, I have mentioned that whenever we write a program, we should check for boundary conditions. This program won't work for negative numbers.

How to make it work for negative numbers?
This is your assignment.

Request: Please take the quiz or leave your comment to help me make this site more useful. Thanks

No comments: