• 0

Recursion


Question

Hi guys. Learning some Java and came across the subject of recursion. There was a snippet of code here which is basically recursion at play:

 

 
public class main {
public static void main(String[] args) {
 
long num;
 
num = fact(5);
 
System.out.println(num);
 
}
 
public static long fact(long n) {
if(n <= 1) 
return 1;
else
return n * fact(n-1);
}
}
Link to comment
https://www.neowin.net/forum/topic/1167889-recursion/
Share on other sites

11 answers to this question

Recommended Posts

  • 0

The running total is held on the stack. Every time a function is called, it pushes a new "frame" on the stack (memory region holding its parameters and local variables), and every time a function returns, it pops its frame from the stack. A simple program like this:

void sayHello() { System.out.println("Hello"!); }

void main() { SayHello(); }
Executes like so:
main()
     -> sayHello()
              -> System.out.println("Hello");
                     -> (... unknown implementation of println ...)

Your function fact() calls itself until the value passed is 1, so it executes like so:

fact(5)
    -> fact(4)
           -> fact(3)
                  -> fact(2)
                         -> fact(1)

fact(1) evaluates to 1 and returns.

fact(2) evaluates to 2 * fact(1), which is now 2 * 1. It returns 2. 

fact(3) evaluates to 3 * fact(2), which is now 3 * 2. It returns 6.

etc.

hence fact(5) evaluates to 120.

 

As you can see, there is no variable in the program that explicitely holds the running total; rather it is an implicit variable held on each stack frame representing the return value of each function call. It is a bit hard to understand until you do some assembly and see how this happens under the hood.

 

The stack is a very limited memory region - typically 1MB. Abusing recursion is the most typical way of blowing up the stack, a bug referred to as a stack overflow.

  • Like 2
Link to comment
https://www.neowin.net/forum/topic/1167889-recursion/#findComment-595849741
Share on other sites

  • 0

 

Hi guys. Learning some Java and came across the subject of recursion. There was a snippet of code here which is basically recursion at play:

 
public class main {
public static void main(String[] args) {
 
long num;
 
num = fact(5);
 
System.out.println(num);
 
}
 
public static long fact(long n) {
if(n <= 1) 
return 1;
else
return n * fact(n-1);
}
}

Stop repeating yourself....

Not sure if there is a question in here.. but basically recursion is the act of repeating..

so like

private void main()
{
   minusTo1(100);
}


private void minusTo1(int num)
{
  //Check if num - 1 == 1. 
  if (--num != 1)
    return minusTo1(num);
  else
    return 1;
}

 

Link to comment
https://www.neowin.net/forum/topic/1167889-recursion/#findComment-595848245
Share on other sites

  • 0

did ask for an explantion (apparently, it decided to delete that massive paragraph I wrote for some strange reason) on how this code actually works as I wasn't sure how exactly the method managed to return 120 as I couldn't see where the multiplication was actually happening, even in the debugger I couldn't see a hidden variable holding the total figure as it went around. Also, I wasn't entirely sure how exactly it worked. 

 

I believe Firey's example helps me get the concept of recusion better, but I still don't understand where exactly it did the multiplication or where the variable was held?

Link to comment
https://www.neowin.net/forum/topic/1167889-recursion/#findComment-595848269
Share on other sites

  • 0

did ask for an explantion (apparently, it decided to delete that massive paragraph I wrote for some strange reason) on how this code actually works as I wasn't sure how exactly the method managed to return 120 as I couldn't see where the multiplication was actually happening, even in the debugger I couldn't see a hidden variable holding the total figure as it went around. Also, I wasn't entirely sure how exactly it worked. 

 

I believe Firey's example helps me get the concept of recusion better, but I still don't understand where exactly it did the multiplication or where the variable was held?

Recursion is basically the act of repeating a function until a desired result is met.  I personally use it for retries.  Instead of having to duplicate code.  I will re-call a function (that I am in) to preform a retry.  Kind of like:

int retries = 1;

SendMyData(string data)

{

    //try to send data

    

    //if it fails, check if retries > 0, if so -1 from retries

   //and call SendMyData() passing in the data we got the first time

   

   //if retries is 0, then don't do anything

}

Because reties will already be set to 0, we will not run the function again after it is called the second time.

And because we don't have any code at the bottom to run, it won't duplicate anything.

Link to comment
https://www.neowin.net/forum/topic/1167889-recursion/#findComment-595848295
Share on other sites

  • 0

all lies in this line :

return n * fact(n-1);

return will be done when "all" calculation on the right will be finished, as it's a recursive function that "terminates" (and returns 1) when n is lower or equal than 1. The actual calculation is this one :

 

fact(5) => return ((((5 * fact(4)) * fact(3)) * fact(2)) * 1;

 

As everything is a multiplication in this case, it's equal to 5 * 4 * 3 * 2 * 1 = 120 

 

Hope it helps :) (and that i didn't get anything wrong :P...)

  • Like 2
Link to comment
https://www.neowin.net/forum/topic/1167889-recursion/#findComment-595848309
Share on other sites

  • 0

fact(5) => return ((((5 * fact(4)) * fact(3)) * fact(2)) * 1;

Well technically this is not correct. The calculation is 5 * 4 * 3 * 2 * 1, not 5 * fact(4) * fact(3) * fact(2) * 1, which would give a much larger number.

 

A more correct and graphical way of putting it would be:

fact(5) = 5 * fact(4)
              fact(4) = 4 * fact(3)
                            fact(3) = 3 * fact(2)
                                          fact(2) = 2 * fact(1)
                                                        fact(1) = 1
Link to comment
https://www.neowin.net/forum/topic/1167889-recursion/#findComment-595850333
Share on other sites

This topic is now closed to further replies.
  • Posts

    • After I installed KB5095093, the volume on my ARM laptop won't go above 20%. It's stuck on the hearing protection level, which is pretty much useless if you want to listen to anything. I rolled back.
    • Amazon Prime Day slashes Samsung's newest Galaxy Watch Ultra by 45 percent by Karthik Mudaliar Samsung’s flagship Android smartwatch has received one of its steepest Prime Day cuts. Amazon has dropped the 2025 Samsung Galaxy Watch Ultra in Titanium Blue to $357.24, saving buyers around $292 from its $649.99 list price. That's a 45 percent discount (purchase link below). The 47mm Galaxy Watch Ultra uses a titanium casing and a 1.5-inch Super AMOLED display with a resolution of 480 x 480 and peak brightness of 3,000 nits. It includes LTE connectivity, Bluetooth 5.3, Wi-Fi, NFC, and dual-frequency L1+L5 GPS for more accurate outdoor route tracking. The 2025 model has 64GB of storage, a 590mAh battery, sapphire crystal glass, 10ATM water resistance, IP68 protection, and MIL-STD-810H durability testing. Its health and fitness tools include heart rate monitoring, sleep coaching, Energy Score, Running Coach, body composition analysis, temperature sensing, and ECG support, where available. This model is best suited to Android users who regularly run, hike, cycle, or train outdoors and want cellular access without carrying a phone. The larger battery, rugged construction, bright display, and dedicated Quick Button also make it a stronger option than Samsung’s regular Galaxy Watch models for extended workouts and demanding environments. Grab the Titanium Blue Galaxy Watch Ultra before the Prime Day price resets: Samsung Galaxy Watch Ultra (2025) [Sold and Shipped by Amazon] Good to know This Amazon deal is U.S. specific, and not available in other regions unless specified. We only use first-party seller links (at the time of article publishing); ensure that you purchase from a first-party seller link only. Check out Today's Deals on Amazon | or our recent tech deals. Become a Prime member (for Students or SNAP) via Neowin Get Prime Access - Prime for half price (for qualifying Medicaid, EBT, SNAP) Subscribe to Prime Video, Audible Plus, Music Unlimited or Kindle Unlimited via Neowin As an Amazon Associate, we earn from qualifying purchases.
    • Google begins rolling out its post-Epic Play Store billing model next week by Karthik Mudaliar Google has confirmed that its redesigned Play Store billing and fee structure will take effect on June 30, 2026, in the United States, the United Kingdom, and the European Economic Area. The changes will let eligible developers offer their own payment systems or send users to an external website for purchases, while separating Google’s platform service fee from the cost of using Google Play Billing. The rollout puts concrete dates and detailed rate cards behind the broader Android policy overhaul Google announced in March. That announcement followed a proposed settlement with Epic Games intended to resolve their long-running disputes over app distribution and payments, although the U.S. portion of the agreement still requires court approval. Under the new billing choice program, developers selling digital content or services can display an alternative payment option alongside Google Play Billing. They may also direct users to their own websites to complete a purchase. Developers can use Google’s standard payment-choice screen or design one that complies with the company’s user-interface rules. Choosing another payment processor does not eliminate Google’s cut altogether. The company will continue charging a service fee for transactions associated with apps distributed through Google Play, regardless of whether payment is handled by Google, an alternative provider, or a developer’s website. Google argues that this fee covers the value and infrastructure provided by Android and the Play Store. For developers earning up to $1 million annually, the service fee will generally be 10 percent. That rate also applies to auto-renewing subscriptions. When Google Play Billing is used in the U.S., U.K., or EEA, Google will add a separate 5 percent billing fee, and developers processing payments elsewhere will not pay that additional charge. This means Google’s familiar flat 30 percent commission is disappearing, but developers will not necessarily see a dramatic reduction on every transaction. An in-app purchase from an existing user processed through Google Play Billing can still reach a combined 30 percent. The biggest savings are likely to come from subscriptions, smaller developers covered by the $1 million tier, and companies able to move customers to their own payment infrastructure. Google is also offering lower rates through its Apps Experience and revamped Games Level Up programs. Apps and games that satisfy the company’s requirements can qualify for 15 percent service fees on new-install transactions and 20 percent on existing-install transactions. The criteria include performance and reliability standards, support for additional Android device categories, and selected platform features. Those program rates are scheduled to become available in the initial markets and Australia on September 30. For consumers, the immediate effect will depend on whether developers adopt alternative payments and pass any savings on through lower prices. For developers, however, June 30 begins a more flexible but considerably more complicated Play Store economy in which distribution, billing, install dates, revenue thresholds, and program participation can each affect Google’s final cut. Google is also separately developing a Registered App Stores program designed to simplify the installation of qualifying third-party stores. That initiative is expected to arrive with a major Android release later in 2026 and will launch outside the U.S. first. Google says the rest of the world will receive the changes by September 30, 2027, although billing rates for markets outside the US, UK, and EEA have not yet been announced.
    • 38% off a super insane price is still an INSANE price.
  • Recent Achievements

    • Dedicated
      Scoobystu earned a badge
      Dedicated
    • First Post
      Tom Schmidt earned a badge
      First Post
    • One Month Later
      D0nn13 earned a badge
      One Month Later
    • Rookie
      +ChiefOfNeo went up a rank
      Rookie
    • One Year In
      Tom Schmidt earned a badge
      One Year In
  • Popular Contributors

    1. 1
      +primortal
      464
    2. 2
      +Edouard
      177
    3. 3
      PsYcHoKiLLa
      124
    4. 4
      Michael Scrip
      81
    5. 5
      Xenon
      76
  • Tell a friend

    Love Neowin? Tell a friend!