Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

recursive functions - why not an infinite loop?

Tags:

javascript

So this is apparently a valid bit of code, but I can't figure out how the second call to power can ever be completed if the exponent argument is anything besides 0.

function power(base, exponent) {
  if (exponent == 0)
    return 1;
  else
    return base * power(base, exponent - 1);
}

From: https://i.sstatic.net/Jin6c.jpg

like image 207
max pleaner Avatar asked Apr 27 '26 09:04

max pleaner


1 Answers

Because the second call will keep calling with smaller numbers in exponent, until it reaches 0, and then return 1, and roll back aggregating the result ...

I think you'll have to do some reading on recursion :)

Here's a simple case of how it'll look:

power(2,2) 
 power(2,1) 
    power(2,0) 
       return 1 
    return 2*1 = 2 
 return 2*2 = 4 

Taken and modified from this page.

Try this page for an animated view of the recursion (didn't work for me, it's an old page, needs java, and I don't have it installed on my machine ...)


Edit:
It was bothering me I couldn't find any simple example of this, so here's a quick console program that might help you visualize how this is working :

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace SO_Console
{
    class Program
    {
        static void Main(string[] args)
        {
            int base_value = 0;
            int exponent = 0;
            string[] parts = new string[2];
            int result = 0;
            Console.Out.WriteLine("Please enter the Power to calculate in this format: x^y "
            + Environment.NewLine + "(where x is the base (int) and y is the exponent (int)."
            + Environment.NewLine);

            var temp = Console.ReadLine();
            if (!string.IsNullOrWhiteSpace(temp))
            {

                parts = temp.Split('^');
                if (parts.Length != 2)
                InvalidInput();
            }
            else
            InvalidInput();


            if (Int32.TryParse(parts[0], out base_value) && Int32.TryParse(parts[1], out exponent))
            result = Power(base_value, exponent, "");
            else
            InvalidInput();

            Console.Out.WriteLine(Environment.NewLine + "Final result = {0}", result);


            Console.Out.WriteLine(Environment.NewLine + "Hit any key to quit.");
            Console.Read();

        }

        /// <summary>
        /// Recursive call to calculate Power x^y
        /// </summary>
        /// <param name="base_value">The base</param>
        /// <param name="exponent">The exponent</param>
        /// <param name="padding">Padding, for output.</param>
        /// <returns></returns>
        private static int Power(int base_value, int exponent, string padding)
        {
            Console.Out.WriteLine(string.Format("{2}Power called with: {0}^{1}", base_value, exponent, padding));
            Thread.Sleep(750);

            if (exponent == 0)
            {
                Console.Out.WriteLine("{0}{1}Base case reached, returning 1.{0}", Environment.NewLine ,padding);
                return 1;
            }
            else
            {
                var return_value = base_value * Power(base_value, exponent - 1, padding + "  ");
                Console.Out.WriteLine("{0}Going back in the recursion, returning {1}.", padding, return_value);
                Thread.Sleep(750);
                return return_value;
            }
        }

        /// <summary>
        /// Inform user about bad input and quit.
        /// </summary>
        private static void InvalidInput()
        {
            Console.Out.WriteLine("Invalid input.");
            return;
        }
    }
}

You can just paste and run it, and your results will look something along:

outputsamuple

Edit 2:
I've written an article about this, explaining in details what happens why where. You're welcome to have a look at it here : simple power recursion, console application.

like image 110
Noctis Avatar answered Apr 28 '26 22:04

Noctis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!