Reputation: 4297
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?
Upvotes: 0
Views: 4531
Reputation: 1
Function Invert (ch:string) : string;
begin
if ch='' then
Invert:=''
else
{get the last letter of the string + eliminate it and execute the function}
Invert:=copy(ch,length(ch),1)+Invert(copy(ch,1,length(ch)-1));
end;
Upvotes: 0
Reputation: 42483
Function Invert (N:integer; word:string) : string;
begin
if N=0 then
Invert:=''
Else
Invert:= word[N] + Invert(N-1,word);
end;
Upvotes: 3
Reputation: 128899
I don't do Pascal, but a typical (simple) recursive reverse, in pseudo-code, looks like:
function reverse(word)
if empty(word) return ""
else return reverse(withoutFirstLetter(word)) + firstLetterOf(word)
Upvotes: 2