Given a list of numbers such as: 3, 5, 16, 47, 91 or: 16, 47, 91, 3, 5 (it doesn't matter if they are in order) the task is to reverse them i.e. 91, 47, 15, 5, 3 or 5, 3, 91, 47, 16.
For this problem we will store the numbers in an array:
var array[1..5] of integer;
We can then use a for loop to move through the list number by number and copy it into another array. We need to start at the last number in the list and copy it into the first cell of the new list, and then copy the second-last in the original list to the second cell in the new list, and so on.
To do this we will use:
for i:= 1 to length(list) do...
We will also use a counter that we will initialize to the index of the last cell in the array and then reduce it by 1 in each cycle of the for loop.
var forward_counter, backward_counter, i: integer;
//long variable names - clumsy but better
than i and j
number_list, reversed_list:array[1..5] of integer;
output_message:string;
begin
output_message:=''; //initialize
message to empty string
number_list[1]:=3;
//initialize array
number_list[2]:=5;
number_list[3]:=16;
number_list[4]:=47;
number_list[5]:=91;
backward_counter:=length(number_list);
for forward_counter:= 1 to length(number_list) do
begin
reversed_list[forward_counter] := number_list[backward_counter];
dec(backward_counter);
end;
for i: 1 to length(reversed_list) do
//create message from reversed list
output_message:=output_message+IntToStr(reverse_list[i]) + ' ';
showmessage(output_message);
end;
Press the Back Button