How to insert an element at a specific index in an array with Pascal

1 Answer

0 votes
program InsertElementInArray;

type
  TArray = array[1..100] of Integer;

var
  arr: TArray;
  size, i, index, val: Integer;

begin
  { Initialize the array and its size }
  size := 5;
  arr[1] := 7;
  arr[2] := 6;
  arr[3] := 9;
  arr[4] := 1;
  arr[5] := 4;

  { Specify the index and value to insert }
  index := 3;
  val := 100;

  { Shift elements to the right }
  for i := size downto index do
    arr[i + 1] := arr[i];

  { Insert the new element }
  arr[index] := val;

  { Increase the size of the array }
  size := size + 1;

  for i := 1 to size do
    Write(arr[i], ' ');
end.

 
 
(*
run:
 
7 6 100 9 1 4 
 
*)

 



answered Feb 20, 2025 by avibootz

Related questions

1 answer 92 views
1 answer 128 views
1 answer 105 views
1 answer 118 views
...