[Q#12771868][A#12772008] How to write Fibonacci Java program without using if
https://stackoverflow.com/q/12771868
What is the code to write in int Fibonacci (int n) without using "if" like they did here Java recursive Fibonacci sequence ? I tried to write this but it is wrong : Because in this program the list will be 1 1 2 3 5 8 and not 0 1 1 2 3 5 8 Here is the program I tried to write:
Answer
https://stackoverflow.com/a/12772008
Your program is entirely correct; all you need to change is the location of the print statement: Alternatively, print g instead of f.
APIzation
public static void main(String[] args) {
int f = 0;
int g = 1;
for(int i = 1; i <= 10; i++)
{
System.out.print(f + " ");
f = f + g;
g = f - g;
}
System.out.println();
}
package com.stackoverflow.api;
public class Human12772008 {
public static void computeFibonacci(int n) {
int f = 0;
int g = 1;
for (int i = 1; i <= n; i++) {
System.out.print(f + " ");
f = f + g;
g = f - g;
}
System.out.println();
}
}
package com.stackoverflow.api;
/**
* How to write Fibonacci Java program without using if
*
* @author APIzator
* @see <a href="https://stackoverflow.com/a/12772008">https://stackoverflow.com/a/12772008</a>
*/
public class APIzator12772008 {
public static void writeProgram() {
int f = 0;
int g = 1;
for (int i = 1; i <= 10; i++) {
System.out.print(f + " ");
f = f + g;
g = f - g;
}
System.out.println();
}
}