How to reverse elements of an array in Pascal?

Member

by orpha , in category: Other , 2 years ago

How to reverse elements of an array in Pascal?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by ida.windler , 2 years ago

@orpha  In order to flip a one-dimensional array, you need to read/rewrite it from the reverse side.

Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
var mas1: array[1..10] of integer; 
    mas2: array[1..10] of integer; 
    i: integer;
begin
  for i:= 10 downto 1 do
    begin
       mas2[10-i+1]:= mas1[i];
    end;   

  for i:= 1 to 10 do
     writeln(mas2[i]);
end;

by austyn.beer , 10 months ago

@orpha 

To reverse elements of an array in Pascal, you can use the following code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
program ReverseArray;

var
  arr: array[1..10] of integer;  // example array of integers
  i, n: integer;

begin
  // read in the array elements
  writeln('Enter the elements of the array:');
  for i := 1 to 10 do
    readln(arr[i]);

  // reverse the array
  n := length(arr);
  for i := 1 to n div 2 do
  begin
    arr[i] := arr[i] + arr[n-i+1];
    arr[n-i+1] := arr[i] - arr[n-i+1];
    arr[i] := arr[i] - arr[n-i+1];
  end;

  // display the reversed array
  writeln('The reversed array is:');
  for i := 1 to 10 do
    writeln(arr[i]);
end.


In this program, we first read in the elements of the array using a for loop. Then, we use another for loop to reverse the array. Inside the loop, we swap the ith and (n-i+1)th elements of the array using a temporary variable. Finally, we display the reversed array using another for loop.