Home > OS >  I want to create a Fibonacci sequence using a for loop, but the integers are not adding up
I want to create a Fibonacci sequence using a for loop, but the integers are not adding up

Time:04-06

procedure TForm1.Button1Click(Sender: TObject);
var
  term1: integer;
  term2: integer;
  term3: integer;
  j: integer;
begin
  term1 := (0);
  term2 := (1);
  for j := 1 to 100 do;
  begin
    term3 :=( term1   term2);
    Memo1.Text:=inttostr(term3);

    term1 := term2;
    term2 := term3;
  end;
end;

end.

This is what I have so far, but term1 and term2 don't want to add up. I have tried some different things, but for some reason the integers never want to add up.

CodePudding user response:

You have an erroneous ; on your loop that you need to remove:

for j := 1 to 100 do;
                    ^

CodePudding user response:

There are several problems with your code

  1. The semicolon after for j := 1 to 100 do prevents your next code that is withing begin..end block to be run in a loop. Why? The code that is to be run in each cycle of for loop is the one that follows the do until the first semicolon. Since you put semicolon just after the do this basically means that empty block of code is ran in a loop. Your begin..end block comes after that. Removing the semicolon after do will fix that.
  2. You are using Memo1.Text:=inttostr(term3); to write the result into Memo. The problem with this is that this will rewrite entire text of the Memo every time so you will end up with only one line showing the last number. You should use Memo1.Lines.Add(inttostr(term3)); instead so that new line is added each time.
  3. Lastly you are using Integer type for your variables. Since numbers in Fibonacci sequence grows very fast you will quickly exceed the maximum value that can be stored in Integer which in Delphi is Signed 32 bit Integer with a max value of 2147483647. You will have to use bigger integer types like 64 bit Integer type and since you are only dealing with positive numbers you should therefore use Unsigned 64 bit Integer that in declared in Delphi by UInt64 type. You can read more about Delphi default Integer types in documentation. Unfortunately not even UInt64 will is big enough for value of all first 100 numbers of Fibonacci sequence. So you will have to use one of the BigIntegers libraries for Delphi to do this properly. There are several of them available on internet.
  • Related