Stranger Stranger - 4 months ago 28
Pascal Question

Reversing a string in a recursive way

I want to reverse a string using a recursive function, here is my code:

Program InvertTheString;
var n:integer;word:string;

Function Invert (N:integer; word:string) : string;
begin
if N=1 then
Invert:=word[N]+Invert
Else
Invert:=Invert(N-1,word);
end;

BEGIN
readln(word);
n:=length(word);
writeln (Invert(N,word));

writeln;write('Press Enter To Exit...');
readln;
END.


But it is not working, where is worng?

Answer
Function Invert (N:integer; word:string) : string;
begin
     if N=0 then
        Invert:=''
     Else
        Invert:= word[N] + Invert(N-1,word);
end;
Comments