Task: given two arrays of the same length. Write a recursive function that compares the elements of the array and if everything came together, then true, and if not, false. The program does not work correctly. In this case, I tried to replace the second element of the array b with "2", but the result is still true. Tell me what's wrong?

var a:array[0..4] of integer; b:array[0..4] of integer; i:integer; function check(a,b:array of integer;i:integer):boolean; begin if a[i]=b[i] then begin result:=true; check(a,b,i+1); end else begin result:=false; exit; end; end; begin for i:=0 to 4 do a[i]:=i; for i:=0 to 4 do b[i]:=i; b[1]:=2; writeln(check(a,b,0)); for i:=0 to 4 do writeln(a[i], ' = ' , b[i]); readln; end. 
  • > Tell me what's wrong? why do you think something is wrong? - DreamChild
  • @DreamChild Because the program is not working properly. El a [1] = 1, and el b [1] = 2, i.e. they do not match, but the program's output results in true, although it should false - 111xbot111
  • then write it in the condition - you do not offer to guess for you that you are not satisfied with the behavior of your code? - DreamChild
  • @DreamChild, I beg your pardon, corrected - 111xbot111

1 answer 1

The Check function needs to be rewritten as:

 function Check(Arr1, Arr2: array of integer; n: integer): Boolean; begin if (Length(Arr1) = n) or (Length(Arr2) = n) then begin if Length(Arr1) = Length(Arr2) then Result := True else Result := False; // массивы разной длинны end else if Arr1[n] = Arr2[n] then Result := Check(Arr1, Arr2, n + 1) else Result := False; end; 

PS: Do not use names that match the names of global variables for function parameter names ( a , b , i in your case) - this can end badly :)

  • And you can ask: if Length (Arr1) = Length (Arr2) - this is why you need to write like this? After all, we are equal by default? - 111xbot111
  • Well, suddenly you want to compare arrays of different lengths. :) Without this check, the function will return True if the beginning of a long array matches the entire length with a short array. I hope I clearly described the situation? - kot-da-vinci
  • @ 111xbot111 You have heh in the function that says array of integer and not array[0..4] of integer . So anything can come to the entrance) - kot-da-vinci
  • @ kot-da-vinci, yeah, I get it. Thank! - 111xbot111