Recursion in Java

Vinnu Mukhi
1 min readMay 28, 2021

Factorial in Java

package com.company;

public class recursion {
static int factorial(int n){
if(n==0 || n==1){
return 1;
}
else{
return n*factorial(n-1);
}
}
public static void main(String[] args) {
int n=5;
System.out.println("The value of factorial n is: "+ factorial(n));

}
}
Output: The value of factorial n is: 120

Iterative factorial in Java!

package com.company;

public class recursion {
static int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
static int factorial_iterative(int n){
if(n==0 || n==1){
return 1;
}
else{
int product= 1;
for(int i=1; i<=n; i++){
product*=i;
}
return product;
}
}
public static void main(String[] args) {
int n=5;
System.out.println("The value of factorial n is: "+ factorial(n));
System.out.println("The value of factorial n is: "+factorial_iterative(n));

}
}
Output: The value of factorial n is: 120
The value of factorial n is: 120

Fibonacci Series in java

package com.company;

public class recursion {
public static void main(String[] args) {
int n1 = 0, n2 = 1;
System.out.print(n1+ " , "+ n2);
for (int i = 0; i < 10; i++) {
int c = n1 + n2;
System.out.print(" , " + c);
n1 = n2;
n2 = c;
}
}
}
Output: 0 , 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 , 55 , 89

--

--

Vinnu Mukhi
0 Followers

I'm a Computer Science Student from Indore (India) and I'm Sharing all my learnings here.