Program In Java
Fibonacci series in Java
1. class Fibonacciseries
{ {
2. public static void main(String args[])
1. {
2. int p1=0,p2=1,p3,i,count=9;
3. System.out.print(p1+" "+p2);//printing 0 and 1
4.
5. for(i=2;i<count;++i)//loop starts from 2 because 0 and 1 are already printed
6. {
7. p3=p1+p2;
8. System.out.print(" "+p3);
9. p1=p2;
10 p2=p3;
11 }
}}}
}}
wi
w
Using recursion
1. class Fibonacciseries1
2. {
3. static int p1=0,p2=1,p3=0;
4. static void printFibonacci(int count)
5. {
6. if(count>0)
7. {
8. p3 = p1 + p2;
9. p1 = p2;
10. p2 = p3;
11. System.out.print(" "+p3);
12. printFibonacci(count-1);
13.
}
14. }
15. public static void main(String args[])
16. {
17. int count=9;
18. System.out.print(p1+" "+p2);//printing 0 and 1
19. printFibonacci(count-2);//n-2 because 2 numbers are already printed
20. }
21. }
Comments
Post a Comment