Borland Pascal Wiki
Advertisement
 This script page was blocked. The script was reviewed and it works perfectly so this page doesn't need anymore editing.

These scripts reverse a number vector in three ways:

  1. Using a second vector
  2. Without using a second vector
  3. Reading it from the keyboard backwards

Variant 1, using a second vector[]

var v,v2:array[1..50] of integer;
    n,i:integer;
begin
 write ('n='); readln (n);
 for i:=1 to n do
 read (v[i]);
 for i:=n downto 1 do
 v2[n-i+1]:=v[i];
 for i:=1 to n do
 write (v2[i],' ');
 readln;
end.

Explanation[]

First, we read the vector from the keyboard.

Then, the variable i will travel backwards in the v vector and will assign to the reversed vector v2 at the position n-i+1 the number contained in v[i]. This explains why n-i+1:

n=5;
v=[1, 2, 3, 4, 5];
when i is 5, n-5+1 = 5-5+1 = 0+1=1;
when i is 4, n-4+1 = 5-4+1 = 1+1=2;
when i is 3, n-3+1 = 5-3+1 = 2+1=3;
when i is 2, n-2+1 = 5-2+1 = 3+1=4;
when i is 1, n-1+1 = 5-1+1 = 4+1=5;

Variant 2, without using a second vector[]

var v:array[1..50] of integer;
    n,i,aux:integer;
begin
 write ('n='); readln (n);
 for i:=1 to n do
 read (v[i]);
 for i:=1 to n div 2 do
 begin
 aux:=v[n-i+1];
 v[n-i+1]:=v[i];
 v[i]:=aux;
 end;
 readln;
end.

Explanation[]

First, we read the vector from the keyboard. Then, using the auxiliary variable reversing method to replace the reverse the position of the variables in the vector. Here is how it works:

n=10
v=[1,2,3,4,5,6,7,8,9,10] 
The variable i will travel from position 1 to position 10 div 2 = 5
when i is 1, v[1] will be replaced with v[10] and vice-versa when i is 2, v[2] will be replaced with v[9] and vice-versa when i is 3, v[3] will be replaced with v[8] and vice-versa when i is 4, v[4] will be raplaced with v[7] and vice-versa when i is 5, v[5] will be replaced with v[6] and vice-versa
The cycle stops here. If the cycle would continue, the resulting vector will be the same as the inputed vector because the elements would be reversed again.

Variant 3[]

! This script may be useful only when reading vectors from the keyboard.

var v:array[1..50] of integer;
    n,i:integer;
begin
 write ('n='); readln (n);
 for i:=n downto 1 do
 read (v[i]);
 readln;
end.

Explanation[]

This script reads the vector backwards. So, if the user inputs 1,2,3,4,5, then 1 will go on the last position and 5 will go on the first position.

See also[]

Advertisement