The basic logic behind the Fibonacci series is you have to add two previous numbers and the sum of these two numbers is the third number and these series continue with the increment (++i).
In this post, we are doing some changes in the Fibonacci series code and examine what type of output are we getting. If you want to know more about the Fibonacci series then click on this Fibonacci series in java.
Cases
Here the come cases that we are taken and check what output are we getting.
1. Change (++i) to (i++)
Code (Condition ++i)
public class fibonaccitest1 {
public static void main(String[] args) {
int a1=0;
int a2 = 1;
int a3;
int i;
int count=10;
System.out.print(a1+" "+a2);
for(i=2;i<count;++i){
a3=a1+a2;
System.out.print(" "+a3);
a1=a2;
a2=a3;
}
}
}
Output
0 1 1 2 3 5 8 13 21 34
Code (Condition i++)
public class fibonaccitest1 {
public static void main(String[] args) {
int a1=0;
int a2 = 1;
int a3;
int i;
int count=10;
System.out.print(a1+" "+a2);
for(i=2;i<count;i++){
a3=a1+a2;
System.out.print(" "+a3);
a1=a2;
a2=a3;
}
}
}
Output
0 1 1 2 3 5 8 13 21 34
Conclusion
We have seen that after making some changes in the condition there is no change in the output.
If you know why this happens then you can tell it in the comment box.
2. let a3 = a2 and a2 = a1.
Code
public class fibonaccitest1 {
public static void main(String[] args) {
int a1=0;
int a2 = 1;
int a3;
int i;
int count=10;
System.out.print(a1+" "+a2);
for(i=3;i<count;i++){
a3=a1+a2;
System.out.print(" "+a3);
a3=a2;
a2=a1;
}
}
}
Output
0 1 1 0 0 0 0 0 0
Conclusion
Why we get this output? We know that at the start we assign a1= 0 and a2 = 1. Now after the "for" statement we write a3 = a1 + a2 but a3 =a2 and a2 = a1 that's why after 3 digits, code will print 0.
0 Comments