Factorial of a given number
Factorial is a positive integer that is the result of the multiplication of all integers that are less than equal to the given number.
For example, the Factorial of 5 is 54321=120.
Using Iterative Function
Following are steps for the Iterative function.
- Used for loop to iterate until give number is matched.
- Declared temporary variable(result) that holds result, with default value 1
- Multiply the result with each iterated value and assign it to result
- Finally, Return the result
Here is a program in java
public class Factorial {
public static void main(String[] args) {
int number = 5;
System.out.println(iterative(number));
}
// Iterative Function
public static int iterative(int n)
{
int result = 1;
for (int i = 1; i <= n; i++)
result *= i;
return result;
}
}
Output:
120
Using Recursive Function
Following are the steps
- Write a function that returns an integer
- Write a condition to stop the execution from a function
- Multiplication of numbers with a recursive function.
- Recursive Function call itself with decrement value by 1,
- Finally, Returns the result.
package com.recursion;
public class Factorial {
public static void main(String[] args) {
int number = 5;
System.out.println(recursive(number));
}
// Recursive Function
public static int recursive(int n) {
if ((n == 0) || (n == 1))
return 1;
else {
return n * recursive(n - 1);
}
}
}
Output:
120