Recursive Functions in C#

April 13, 2005 by  
Filed under .NET, Daily Ramblings, Scripts and Coding

My first recursive function in C#. Woohoo. I remember writing this when I first learned C++. :)

What does it do? It’s the does the Power function. For example, 12^2 would return 144 because it’s 12×12.

public static int Power(int baseNum, int exponent)
{
	int product = 0;

	if(exponent == 0)
		product = 1;
	else if(exponent == 1)
		product = baseNum;
	else
	{
		product = baseNum;
		product *= Power(baseNum, exponent-1);
		Console.WriteLine("Product: " + product);
	}

	return product;
}

[Note] I’m not sure why the slashes are showing up in the last WriteLine statement.. Maybe it’s a safety feature in WordPress..

Related Posts Plugin for WordPress, Blogger...
  • alpha

    I don’t think that this line is necessary:

    else if(exponent == 1)
    product = baseNum;

  • alpha

    I don’t think that this line is necessary:

    else if(exponent == 1)
    product = baseNum;

  • http://daynah.net daynah

    It’s not “necessary”, but it makes the code more efficient. So if the exponent is 1, it’ll just return the baseNum rather than looping through the function again.

  • http://daynah.net daynah

    It’s not “necessary”, but it makes the code more efficient. So if the exponent is 1, it’ll just return the baseNum rather than looping through the function again.