How to limit for loop to print only first few records in list?

Viewed 172

How should I print the first 5 element from list using for loop in Delphi. Below are the sample I created:

p := ['a','b','c','d','e','f','g','h','i'];
for P in p do begin
   showMessage(P);
end

By using this I was able to print all element in the list, but I wanted to print only the first 5. Please help if you know the answer. Thanks.

2 Answers

The code below will do. It make use of an index variable looping from 0 (the first element of an array) to 4 (To get the first 5 elements).

var
  I : Integer;
begin
  var p := ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'];
  for I := 0 to 4 do
      ShowMessage(p[I]);
end;

In other context, since array bounds are not limited to start at 0, and to avoid going out of range, you could use the functions Low(), High() and Min() like this:

for I := Low(p) to Min(Low(p) + 4, High(p)) do  // 5 items at most
    ShowMessage(p[I]);

To use Min() you must add System.Math to the uses clause.

In order to keep the for .. in method, you could use a counter variable:

var
  Count : Integer;
begin
  p := ['a','b','c','d','e','f','g','h','i'];
  Count := 0;
  for P in p do
    begin
      if Count < 5 then
        begin
          ShowMessage(P);
          Inc(Count);
        end;
    end;
end;

Or, more elegantly, use a standard for index loop:

var
  I : Integer;
begin
  p := ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'];
  for I := 0 to High(p) do
    begin
      if I < 5 then
        ShowMessage(p[I]);
    end;
end;
Related