Average calculation is an easy formula to practice your programing skills. We have seen a CLI average calculator program of unlimited numbers, now its time for a GUI project.
Yesterday you have seen a Free Pascal sample code for calculating average of unlimited numbers using Lazarus. We have used a while
do loop to calculate the final result. It is much more easier to create such a program in GUI (Graphical User Interface).
What we will do
In our little program we will have a TEditBox
. The user will type in the numbers and press enter. After pressing enter, the number will be automatically added to the list and the average will be calculated automatically.
We will need the basics of list management- adding item to list (because we will add the input numbers to a ListBox) and the basics of average calculation. And for enhancing the program we also add a Remove from list button [ - ] and a Clear button for clearing the list and starting new calculation.
Tutorial
Add a TEditBox
, TListBox
, 3 TButton
s, 3 TLabel
s. Set their properties like the following:
TEditBox:
Alignment : taRightJustify
Name : edtNumber
TabOrder : 0 (Because we want the focus to be in this component when run.)
TListBox:
Items : (Click the […] button and clear all the lines)
MultiSelect : True
Name : ListBox1
TButton (1):
Caption: Add Number
Name: btnAdd
TButton (2):
Caption: -
Name: btnRemove
TButton (3):
Caption: Clear
Name: btnClear
TLabel (1):
Caption: Number:
TLabel (2):
Caption: The average is:
TLabel (3):
Alignment: taRightJustify
Autosize: False
Caption: 0
Font.Size: 18
Name: lblAverage
Position the components according to the screenshot.
Double click the btnAdd
and enter the commands:
1 | var |
Add the following procedure under {$R *.lfm}
line:
1 | // This procedure calculates the average of the |
Then keep your cursor on CalcAverage()
and press Ctrl+Shift+C. A declaration for the procedure will be created at the top of the code / unit. We can now use the procedure in our code.
Select edtNumber
and go to Object Inspector then click the Events tab. Click the [...]
in front of OnKeyPress
and enter the following command:
1 | begin |
It will add the number input to the list when user presses Enter key from keyboard. With the btnAddClick(edtNumber);
the command in btnAdd
‘s click event is run.
Double click the btnRemove
and enter:
1 | var |
Double click btnClear
and enter:
1 | begin |
Now Run the program (F9 or Run -> Run).
Now input numbers and press enter. You will see the average of the numbers in the lblAverage
.
The code is pretty much self explanatory. For further explanations of the code you can look at the average and list manipulation example. You can also extend the capacity of the program by by declaring sum, count, and average variable in the CalcAverage
procedure, with a variable type of greater capacity.
Downloads
You can download the source code for the tutorial project and executable/EXE files from the links below: