Search code examples
cc++builder-6

Show on the screen n-element of the progression


My task is

Show on the screen n-element of the progression {xi}.

Xi = Xi-1 - 3Xi-2
X0 = 0
X1 = 2
i = [2,n]

Here is done, but I didn't understand this theme very well, so i need some help with it. My code(doesn't work):

void __fastcall TForm1::Button1Click(TObject *Sender)
{
  int n = Edit1->Text.ToInt();
  int i, x;
  if(n==0){
    i=0;
    Label1->Caption = IntToStr(i);
  }
  if(n==1){
    i=2;
    Label1->Caption = IntToStr(i);
  }
  else {
    for(i=2;i<=n;i++){
      x=(i-1)-3*(i-2);
      Label1->Caption = IntToStr(x);
    }
  }
}

It's not very nessesary to write code in C++ Builder


Solution

  • You misunderstood the progression formula. Xi-1 and Xi-2 refer to previous elements calculated in your progression.

    So you need two variables, which will be carrying previous values that you have just calculated. At any given loop, you calculate the current Xi value using the general progression formula, then copy the value of Xi-1 into Xi-2, throwing the previous value of Xi-2. Then you copy the value of Xi (the up to now current value) into Xi-1.

    void __fastcall TForm1::Button1Click(TObject *Sender)
    {
      int n = Edit1->Text.ToInt();
      int i, x;
      int xim1, xim2
      if(n==0){
        i=0;
        Label1->Caption = IntToStr(i);
      }
      if(n==1){
        i=2;
        Label1->Caption = IntToStr(i);
      }
      else {
        xim1 = 2;
        xim2 = 0;
        for(i=2;i<=n;i++){
          x = xim1-3*xim2;
          xim2 = xim1;
          xim1 = x;
        }
        Label1->Caption = IntToStr(x);
      }
    }