What is Recursion ?
Ans: A function in Java can call itself is such calling of function by itself is called recursion.
Ek aisa bnana jo khud ko hi call kare aur tab tk call kare jb tk ki base line touch na kar jaye wo recursion hota hai.
Stack Me FIFO model chlta hai
What is base case ?
where we want to stop our recursion.
public class Recursion2 {
public static int factorialN(int n){
if(n == 0 || n == 1){ // base case
return 1;
}
return n * factorialN(n-1);
}
public static void main(String[] args) {
int n = 4;
System.out.println("Factorial Number of n is:" + factorialN(n));
factorialN(n);
}
}
2nd: Examples:
// Press Shift twice to open the Search Everywhere dialog and type `show whitespaces`,
// then press Enter. You can now see whitespace characters in your code.
public class Recursion1 {
public static void printN(int n) {
if(n == 0){ //base case
return;
}
System.out.println(n);
printN(n-1);
}
public static void main(String[] args) {
int n = 1000;
printN(n);
}
}
Comments
Post a Comment