How to print the first 12 terms of the Fibonacci sequence in reverse in Pascal?

Asked

Viewed 224 times

-1

How to print the first 12 terms of the Fibonacci sequence in reverse in Pascal? Instead of 1 to 12, 12 to 1

program Exercicio_31;

var V:array[3..12]of integer;I,termo1,termo2,novoTermo:integer;

begin


     writeln('Serie de Fibonacci');
     writeln('==================');
     termo1 := 1;
     termo2 := 1;
     writeln(' 1o. termo = ', termo1);
     writeln(' 2o. termo = ', termo2);
     for I:=12 downto 3 do 
     begin
        novoTermo := termo1 + termo2; { o novo termo e a soma dos dois termos anteriores }
        writeln(I:2, 'o. termo = ', novoTermo);
        termo1 := termo2;   {o segundo termo e o primeiro termo no proximo passo }
        termo2:=novoTermo; { o novo termo e o segundo termo no proximo passo }
     end;
     writeln('==================');
     writeln;
     write('Pressione [algo] para prosseguir.');
     readkey;
end.
  • 1

    Apparently it’s a college issue.

  • Yeah, it’s from college.

  • Before asking the question directly, sponge how it tried to arrive at the solution and the problems it found in the implementation. Do not present the question directly without showing any effort.

1 answer

3


The simplest way is to start the iteration already with the value of the 12th number and the 11th number and subtract them until you reach the initial values of the sequence:

program Exercicio_31;

var V:array[3..12]of integer;
I,termo1,termo2,novoTermo:integer;

begin


     writeln('Serie de Fibonacci');
     writeln('==================');
     termo1 := 144;
     termo2 := 89;
     writeln('12o. termo = ', termo1);
     writeln('11o. termo = ', termo2);
     for I:= 10 downto 1 do 
     begin
        novoTermo := termo1 - termo2; { o novo termo e a soma dos dois termos anteriores }
        writeln(I, 'o. termo = ', novoTermo);
        termo1 := termo2;   {o segundo termo e o primeiro termo no proximo passo }
        termo2 := novoTermo; { o novo termo e o segundo termo no proximo passo }
     end;
     writeln('==================');
     writeln;
     write('Pressione [algo] para prosseguir.');
end.

Exit

Serie de Fibonacci

==================
12o. term = 144
11o. term = 89
10th. term = 55
9o. term = 34
8o. term = 21
7o. term = 13
6o. term = 8
5th. term = 5
4o. term = 3
3rd. term = 2
2nd. term = 1
1st. term = 1

==================

Browser other questions tagged

You are not signed in. Login or sign up in order to post.