typecode
PascalRecords/inventory.pas
1program Inventory;
2
3type
4 TProduct = record
5 Id: Integer;
6 Name: string[50];
7 Price: Real;
8 Quantity: Integer;
9 end;
10
11 TInventory = record
12 Items: array[1..100] of TProduct;
13 Count: Integer;
14 end;
15
16var
17 Inv: TInventory;
18
19procedure InitInventory(var I: TInventory);
20begin
21 I.Count := 0;
22end;
23
24function AddProduct(var I: TInventory;
25 AName: string; APrice: Real;
26 AQty: Integer): Boolean;
27begin
28 if I.Count >= 100 then
29 begin
30 AddProduct := False;
31 Exit;
32 end;
33 Inc(I.Count);
34 with I.Items[I.Count] do
35 begin
36 Id := I.Count;
37 Name := AName;
38 Price := APrice;
39 Quantity := AQty;
40 end;
41 AddProduct := True;
42end;
43
44function FindProduct(var I: TInventory;
45 AName: string): Integer;
46var
47 Idx: Integer;
48begin
49 FindProduct := -1;
50 for Idx := 1 to I.Count do
51 if I.Items[Idx].Name = AName then
52 begin
53 FindProduct := Idx;
54 Exit;
55 end;
56end;
57
58function TotalValue(var I: TInventory): Real;
59var
60 Idx: Integer;
61 Total: Real;
62begin
63 Total := 0.0;
64 for Idx := 1 to I.Count do
65 Total := Total +
66 I.Items[Idx].Price * I.Items[Idx].Quantity;
67 TotalValue := Total;
68end;
69
70procedure SortByPrice(var I: TInventory);
71var
72 J, K: Integer;
73 Temp: TProduct;
74begin
75 for J := 1 to I.Count - 1 do
76 for K := J + 1 to I.Count do
77 if I.Items[J].Price > I.Items[K].Price then
78 begin
79 Temp := I.Items[J];
80 I.Items[J] := I.Items[K];
81 I.Items[K] := Temp;
82 end;
83end;
84
85procedure SaveToFile(var I: TInventory;
86 FileName: string);
87var
88 F: TextFile;
89 Idx: Integer;
90begin
91 Assign(F, FileName);
92 Rewrite(F);
93 WriteLn(F, I.Count);
94 for Idx := 1 to I.Count do
95 with I.Items[Idx] do
96 WriteLn(F, Id, '|', Name, '|',
97 Price:0:2, '|', Quantity);
98 Close(F);
99end;
100
101begin
102 InitInventory(Inv);
103 AddProduct(Inv, 'Widget', 9.99, 50);
104 AddProduct(Inv, 'Gadget', 24.95, 30);
105 SortByPrice(Inv);
106 SaveToFile(Inv, 'inventory.dat');
107end.
0WPM
100%Accuracy
00:00Time
0%
Progress