Using Java: While and for loop to generate numbers in the Fibonacci sequence
Tasks:
1. Using your understanding of Fibonacci numbers chalk out how you would use a while loop to generate (and display) numbers in the Fibonacci sequence. The program that you are attempting to write must take a number, n, from the user that tells you how many Fibonacci numbers to display. Write the while loop portion of how you think this would work below. (You do not need to show taking the number n from the user.)
2. Now write the program that takes the number, n, from the user and displays that many numbers in the Fibonacci series.
3. Now rewrite the program using a For loop. What changes are required to make this happen?
Answer 1:
System.out.print(f + " " + s);//
printing 0 and 1
while (i<n) {
//adding first
and second and putting in 3rd
t = f + s;
//printing
3rd
System.out.print(" " + t);
//swapping
values
f = s;
s = t;
i++;
}
Answer 2:
import java.util.Scanner;
public class FixExample {
public static void main(String args[]) {
int f = 0, s = 1, t, i,n;
Scanner sc = new
Scanner(System.in);
System.out.println("Enter how many
number to display");
n=sc.nextInt();
System.out.print(f + " " + s);//
printing 0 and 1
i = 2; // starting from 2 as 0,1 is
printed
while (i<n) {
//adding first
and second and putting in 3rd
t = f + s;
//printing
3rd
System.out.print(" " + t);
//swapping
values
f = s;
s = t;
i++;
}
}
}
Answer 3:
//Just we need to change the for loop in place of while. everything will be same
import java.util.Scanner;
public class FixExample {
public static void main(String args[]) {
int f = 0, s = 1, t, i,n;
Scanner sc = new
Scanner(System.in);
System.out.println("Enter how many
number to display");
n=sc.nextInt();
System.out.print(f + " " + s);//
printing 0 and 1
// starting from 2 as 0,1 is
printed
for (i = 2;i<n;i++) {
//adding first
and second and putting in 3rd
t = f + s;
//printing
3rd
System.out.print(" " + t);
//swapping
values
f = s;
s = t;
}
}
}
Get Answers For Free
Most questions answered within 1 hours.