How to pop the first element of an array in Pascal

2 Answers

0 votes
program RemoveFirstElement;

var
  arr: array of SmallInt; // Declare dynamic array type
  i: Integer;
begin
  // Initialize the array
  SetLength(arr, 5);  
  arr[0] := 1;
  arr[1] := 2;
  arr[2] := 3;
  arr[3] := 4;
  arr[4] := 5;

  // Check if the array is not empty
  if Length(arr) > 0 then
  begin
    // Remove the first element by shifting all elements left
    for i := 0 to High(arr) - 1 do
      arr[i] := arr[i + 1];

    // Resize the array to remove the last element
    SetLength(arr, Length(arr) - 1);
  end;

  // Print the updated array
  for i := 0 to High(arr) do
    Write(arr[i], ' ');
    
  WriteLn;
end.



(*
run:

2 3 4 5 

*)  

 



answered May 2, 2025 by avibootz
edited Jul 5, 2025 by avibootz
0 votes
program RemoveFirstElement;

type
  TIntArray = array of SmallInt; // Declare dynamic array type

// Function to remove the first element from an array
function RemoveFirst(var arr: TIntArray): TIntArray;
var
  i: Integer;
begin
  if Length(arr) > 0 then
  begin
    for i := 0 to High(arr) - 1 do
      arr[i] := arr[i + 1];
      
    SetLength(arr, Length(arr) - 1); // Resize the array
  end;

  RemoveFirst := arr; // Return the modified array
end;

var
  arr: TIntArray;
  i: Integer;
begin
  // Initialize the array
  SetLength(arr, 5);
  arr[0] := 1;
  arr[1] := 2;
  arr[2] := 3;
  arr[3] := 4;
  arr[4] := 5;

  arr := RemoveFirst(arr);

  // Print the updated array
  for i := 0 to High(arr) do
    Write(arr[i], ' ');
    
  WriteLn;
end.



(*
run:

2 3 4 5 

*) 

 



answered May 2, 2025 by avibootz
...