Tuesday, February 10, 2009

What are recursive functions?

We are aware about how functions are defined in C or C++ or Java or.Net.
In which ever case it is, in a programming language we start our process by defining a method or function.
We say Main method is the first method that gets called to start executing an application.
1) Function can expect parameters which is not mandatory.




2) When a function is called it is loaded then into memory with given parameters as well.
3) Function may or may not return a value



4) A function can call an another function or by itself.



5) Recursive function can be defined as a function calling by it self.




Memory structure:-
Let us consider a simple function as



If this is a recursive function (say it calls for it self 3 times) then



Example:-

I have created a .NET windows application for calculating the factorial of a given number.
If input is 5 then output should be 5*4*3*2*1
Code:


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Sample
{
public partial class frmFactorial : Form
{
public frmFactorial()
{
InitializeComponent();
}

private void btnFactorial_Click(object sender, EventArgs e)
{

try
{
//Checking given value is numeric or not
if (!IsNumber(txtFact.Text))
throw new Exception("Enter numeric value for A");
//calling factorial function
MessageBox.Show(Factorial(Convert.ToInt32(txtFact.Text)).ToString());

}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
}
private int Factorial(int argVal)
{
//If input value is greater then one then once call once again
//by multiplying input value with the return value of
//factorial function by sending the value after deducting 1
//from the given input value
if (argVal > 1)
{
argVal = argVal * Factorial(argVal - 1);
}
//returning the final value, which is calculated after multiplying
//recursively
return argVal;
}

private bool IsNumber(string argValue)
{
try
{
//checking if the given value is numeric
Convert.ToInt32(argValue);
return true;
}
catch
{
return false;
}
}
}
}

output:-



No comments: