I've been trying to make a program that will ask user to input elements of an array and then use that array to make a new one whose elements would be every 2nd element of inputted array. This is what I was writing:
program Keanu;
uses crt;
type Arr=array of integer;
var n,i:integer;
A,C:Arr;
begin
writeln('--Enter desired length of array--');
readln(n);
setlength(A,n);
setlength(C,n);
writeln('Elements of array A:');
for i:=1 to n do
readln(A[i]);
writeln('Elements of array C are:');
i:=1;
while (i<=n) do
begin
c[i]:=a[i];
i:=i+2;
end;
write('C = {');
for i:=1 to n do
begin
if c[i]=0 then continue else
begin
write(c[i],' ');
end;
end;
write('}');
readln;
end.
But as you can notice this is far from efficient way to make this program do the job.
First, because my new array will contain blank/empty elements(zeros) which I simply ignored with continue statement and I dont want to do that if possible.
Second,I have problem when inputting an even number for array length.Last element of new array in output window is very small,negative number and he shouldn't be there at all.I know this has to do something with my counter "i" crossing into "undefined" indexes of array.
I also tried replacing while loop with some variations of:
for i:=0 to n do
c[i]:=a[2*i-1] ;
Which is more elegant way but I still get , besides desired result , those large numbers , again because of crossing limits of an array.I suspect this has to be done with proper steps of how new array is made and moving those elements next to each other with no blank elements. So, if anyone can give me some solutions of how to get these loop steps and limits into right order and make efficient,shortest algorithm, and preferably without using while loop if possible ,and definitely without ignoring those blank elements of new array.
n div 2elements long and then use two index variables, e.g.ifor reading, andjfor writing, increasingiwith two andjwith one for each loop step.x:=Round(n/2+0.1);wherexis length of new array.stepclause in yourforloop, as infor i := 0 to n - 1 step 2 do, which will loop with 0, 2, 4, and so forth. I personally would switch to awhile i < n doinstead, and incrementiby the desired amount inside the loop. It makes the code more clear, IMO, and prevents overrunning the end of the array. You should also enable range checking ({$R+})and overflow checking ({$Q+}), at least during development, to catch any possible issues.whileloops are more clear and I used them in this case.To be honest I didnt know that Pascal can do custom steps withinforloop, but thank you very much for showing mestep.I understand that dyn.arrays start with index 0 but Im wondering about what if I saidforloop in the end to write me elements of a new array from-1tox?Would array start with : 0 0 and then integer values of inputted array from beginning of program? Would that mean that array[-1],array[-2] are also empty elements although they are not indexed(I think) or assigned any value?