0% found this document useful (0 votes)
7 views2 pages

Labsheet 7a-Recursion Using Stack

The document presents a Java program that calculates the factorial of a number using both recursion and a stack-based approach. It includes a recursive function 'recursiveFactorial' and an iterative function 'factorialWithStack' that simulates recursion using a stack data structure. The main method tests both functions with the number 5 and prints the results.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views2 pages

Labsheet 7a-Recursion Using Stack

The document presents a Java program that calculates the factorial of a number using both recursion and a stack-based approach. It includes a recursive function 'recursiveFactorial' and an iterative function 'factorialWithStack' that simulates recursion using a stack data structure. The main method tests both functions with the number 5 and prints the results.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

RECURSION USING STACK

package recursion;
import [Link];
public class Factorial {

​ ​ // Recursive factorial function


​ public static int recursiveFactorial(int n) {
​ if (n == 0 || n == 1) {
​ return 1;
​ } else {
​ return n * recursiveFactorial(n - 1);
​ }
​ }

​ // Factorial with stack function


​ public static int factorialWithStack(int n) {
​ // Create a stack to simulate recursion
​ int stack = new int[20];
​ [Link](n); // Push the initial value onto the stack
​ int result = 1; // Initialize the result variable to 1

​ // Iterate until the stack is empty


​ while (![Link]()) {
​ int num = [Link](); // Pop a number from the stack

​ // Multiply the result by the popped number


​ result *= num;

​ // If the popped number is greater than 1, push (num - 1) onto the


stack
​ if (num > 1) {
​ [Link](num - 1);
​ }
​ }
​ return result; // Return the factorial result
​ }

​ // Main method to test the recursive and stack-based factorial functions


​ public static void main(String[] args) {
​ int num = 5; // Number for which factorial is calculated
​ // Calculate and print factorial using recursion
​ [Link]("Factorial of " + num + " using recursion: " +
recursiveFactorial(num));

​ // Calculate and print factorial using stack


​ [Link]("Factorial of " + num + " using stack: " +
factorialWithStack(num));
​ }
​ }

You might also like