FIBONACCI SERIES USING RECURTION
- What is fibonacci series ?
- The Fibonacci sequence is a set of integers (the Fibonacci numbers) that starts with a zero, followed by a one, then by another one, and then by a series of steadily increasing numbers. The sequence follows the rule that each number is equal to the sum of the preceding two numbers.
We can handle this series set in many way
For example:-
- Using looping statement
- recursion
- Operator (inc/dec)operator
- Array concept
our previous fibonacci method program in c
click here to see that post 👈👈
Now let's see recursion:-
* In computer science, recursion is a method of solving a computational problem where the solution depends on solutions to smaller instances of the same problem.
*Recursion need function to perform the conditions.
*Recursion function means sub functions ,so if user want to resolve the variable the variables are in global is manmandatory
*Recurtion need loop for when the number series format .
*Loops help to break the looping.
Source code
package fibonacci;
public class fiborecur {
public static int a=0;
public static int b=1;
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(a +"\n"+b);
Recursion ob=new Recursion();
ob.fib(13);
}
}
class Recursion extends
{
int c,x;
void fib(int x)
{
if(x>0)
{
c=a+b;
System.out.println(c);
a=b;
b=c;
this.fib(x-1);
}
}
}
DESCRIPTION OF THE PROGRAM:
* First the main function will call the default a and b value .We already know why we print these two values are beforehand.
* Then next the main function call the method fib().
* we pass the value for the method while the calling time.
* The called method take the value for the given variable.then its check the given condition
* If the given condition is true the inside of the logic starts there work.then the previous two value added and its stored in an another variable is c.
* Then the SOP will the the third variable which means c.
* Now we know to swap the value for the next fibonacci .now we call the fib ( ) method itself by using this.
this.
is the keyword refers to the current object in a method or constructor. The most common use of the this keyword is to eliminate the confusion between class attributes and parameters with the same name.
* By calling the same method again , we subtract the value by 1 inside of the method.
* Whenever that condition is false then the program will exit.
OUTPUT
X =13.
0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
No comments:
Post a Comment