By entering the value 5, it will show me the following information as a result:
0 1 1 2 3 5 8
If I enter the value 6, it will display the following:
0 1 1 2 3 5 8 13
Now what I need is to know how to obtain the last three results of a numeric sequence, that is, taking the first case as an example:
el primero: 3
el segundo: 5
y el último es: 8
In the second case:
El primero: 5
el segundo: 8
y el último valor es: `13`
This is my code:
public class PracticaTesting {
public static void main(String[] args) {
int n,ultimonumero,primero,segundo,i;
Scanner lector = new Scanner(System.in);
do {
System.out.print("Ingrese un número mayor o igual a 1: ");
n = lector.nextInt();
}while(n<=0);
System.out.print("Los " + n + " primeros términos de la serie: ");
primero=0;
segundo=1;
System.out.print(primero + " ");
for(i=0;i<=n;i++){
System.out.print(segundo + " ");
segundo = primero + segundo;
primero = segundo - primero;
}
System.out.println();
}
}
Note: I am using the NetBeans IDE and I already have a variable called defined
ultimonumero
that is where I want to store said information and, together with the variablesprimero
and,segundo
the information should be identified.
Expected result:
The first 5 terms of the series: 0 1 1 2 3 5 8
First: 3 Second: 5 Last number: 8
If you have the opportunity to add new variables you could do it this way, the lastNumber variable is only equal to the second variable at the end of the for loop