Ashref Ashref - 22 days ago 15
Pascal Question

Pascal : inverting a string with recursion

I'm trying to learn recursion in pascal, and i have this code to invert a string with recursion :

Function Invert (ch:string) : string;

begin
if ch='' then
Invert:=''
else

Invert:=copy(ch,length(ch),1)+Invert(copy(ch,1,length(ch)-1));
end;


Can anyone explain to me what's going on here step by step.
Thank you.

Answer

If the string is empty, its inversion is just the empty string; otherwise, the inversion is the last character followed by the inversion of (the string minus its last character).

Fortunately, you have a function that can invert a string: Invert.

Comments