21 October 2005

My First Recursion

I'm so happy I almost cried today. Almost cried, but did not cry. The reason for my joy was because I finally managed to write a recursive function ALL BY MYSELF. It isn't a snazzy function or what-not, but I proved to myself that I finally had a rough understanding of recursion.

I've known recursion for some time, but it wasn't until 10 minutes ago that I understood it. In programming, recursive functions are special functions that solve problems by repeatedly calling itself. It has been taught several times in programming classes, but I never really managed to answer recursive questions without referring to the instructor's sample answer.

But today, while I was doing a little tutorial, I attempted a recursive problem and was able to formulate a perfect solution! I was a little apprehensive when starting to solve it because I hate to be wrong, so I actually wanted to skip it. I'm glad I didn't, and I finally crossed over a little barrier.

For those interested in what problem I actually solved, here it is. It's not a terribly difficult problem, but one which I was delighted to solve anyway.
Give a recursive algorithm for finding the sum
of the first n odd positive integers.
And for those interested, here's the pseudocode I wrote for the correct answer:

FUNCTION oddSum (n: INTEGER) : INTEGER

   IF n = 1 THEN
      oddSum = n
   ELSE
      oddSum = oddSum (n-1) + (n*2-1)
   END IF
END FUNCTION

No comments: