unit BigAdd1F;
//*******************************************************
// Example program demonstrating recursive addition.
//*******************************************************
// Copyright (C) 1998 John Wiley & Sons, Inc.
// All rights reserved. See additional copyright
// information in Readme.txt.
//*******************************************************

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  StdCtrls, Menus;

type
  TBigAddForm = class(TForm)
    MainMenu1: TMainMenu;
    File1: TMenuItem;
    mnuExit: TMenuItem;
    Help1: TMenuItem;
    mnuAbout: TMenuItem;
    NEdit: TEdit;
    Label1: TLabel;
    Label2: TLabel;
    ResultLabel: TLabel;
    CmdCompute: TButton;
    procedure NEditChange(Sender: TObject);
    procedure NumbersOnly(Sender: TObject; var Key: Char);
    procedure CmdComputeClick(Sender: TObject);
    procedure mnuExitClick(Sender: TObject);
    procedure mnuAboutClick(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  BigAddForm: TBigAddForm;

    function BigAdd(n : Double) : Double;

implementation

{$R *.DFM}

procedure TBigAddForm.NEditChange(Sender: TObject);
begin
    CmdCompute.Enabled := (NEdit.Text <> '');
end;

procedure TBigAddForm.NumbersOnly(Sender: TObject; var Key: Char);
begin
    if (Key = #8) then exit; // Backspace.
    if ((Key >= '0') and (Key <= '9')) then exit;
    Key := #0;
end;

procedure TBigAddForm.CmdComputeClick(Sender: TObject);
begin
    ResultLabel.Caption := '';
    Screen.Cursor := crHourGlass;
    Update;

    ResultLabel.Caption := Format('%.6g',
        [BigAdd(StrToFloat(NEdit.Text))]);

    Screen.Cursor := crDefault;
end;

procedure TBigAddForm.mnuExitClick(Sender: TObject);
begin
    Close;
end;

procedure TBigAddForm.mnuAboutClick(Sender: TObject);
const
    CR = #13#10;
    CRCR = #13#10#13#10;
begin
    MessageDlg(
        'This program computes the sum 1 + 2 + 3 + ... + N recursively.' + CRCR +
        'Enter a value and click the Compute button to calculate the sum.' + CRCR +
        'Note that this function can more easily be computed by:' + CR +
        '    N * (N + 1) / 2'
        , mtInformation, [mbOK], 0);
end;

// Use tail recursion removal to compute BigAdd non-recursively.
function BigAdd(n : Double) : Double;
begin
    if (n <= 1) then
        BigAdd := 1
    else
        BigAdd := n + BigAdd(n - 1);
end;

end.
