by Keyvan Nayyeri via Keyvan Nayyeri on 8/14/2007 5:02:04 PM
One of guys at our military office is learning programming from the base at 25!! Sometimes he asks me some questions and wants me to check his codes. Today he showed me one of his codes for Factorial recursive example and asked a few examples!
Seeing his example, I suddenly remembered something that I had read in Code Complete 2 about two silly examples that we see in computer-science textbooks for recursion and they are Factorial and Fibonacci sequence algorithms. Steve McConnell is 100% right in his great book because I've seen many newbie programmers who step in wrong direction after learning recursion with these examples.
I can remember high school and university days when we were studying programming and teachers were giving these two examples to show us how to use recursive algorithms and implement them!
Let me get back to our 25 years old guy to show you why these examples can be silly. After seeing his example, I rewrote his code with an iterative algorithm then asked him how does he think about this new code? And he said: "Yes this is better but I never could predict such a solution after seeing that recursive solution for this problem." Apparently, my Applied Mathematics degree didn't help me to write a better solution and his poor background in mathematics didn't yield to his bad solution. In fact, there was only one reason for this and that was the wrong starting thread that a computer textbook had given to him!
Here I'd like to second Steve's conclusion in his book where he says that these computer textbooks aren't doing any favor for our world!
If you're looking for codes, here they are in C# (both inspired from Code Complete 2 since it's in front of my eyes!):
using System;
using System.Collections.Generic;
using System.Text;
namespace FactorialSample
{
public class Factorial
// Recursive Algorithm
public static int RecursiveFactorial(int number)
if (number == 1)
return 1;
else
return (number * RecursiveFactorial(number - 1));
}
// Iterative Algorithm
public static int IterativeFactorial(int number)
int result = 1;
for (int index = 2; index <= number; index++)
result = result * index;
return result;
Beside this, as a good example of recursion when it's life saver, just take a look at the recursive algorithm that I found for Latin Squares and implemented it in .NET (here and here) or my implementation of 3D Tic-Tac-Toe game in .NET with trees and recursion. Now I feel that I have to revise a computer-science textbook with better examples!
Original Post: Silly Recursion Examples
The content of the postings is owned by the respective author. CSharpFeeds is not responsible for the contents of the postings. This site is automatically generated and cannot be reviewed for abusive content. If you find abusive content on CSharpFeeds, please contact us. Designated trademarks and brands are the property of their respective owners. All rights reserved.