| | |
recursive routines
![]() |
•
•
Join Date: Feb 2008
Posts: 1
Reputation:
Solved Threads: 0
I don't know why the next program doesn't find an element of the array.
delphi Syntax (Toggle Plain Text)
program rec; {$APPTYPE CONSOLE} uses SysUtils; procedure intarray(a:array of integer;longar:integer); begin if longar>=0 then begin write(a[longar],' '); intarray(a,longar-1); end; end; procedure exist (a:array of integer;num2,longar:integer;found:integer); begin if longar>1 then begin if a[longar]=num2 then found:=1 else if longar=1 then found:=0 else exist(a,num2,longar-1,found); end; end; var num2,I,longar,found:integer; a:array[0..9] of integer; begin For I:=0 to 2 do begin a[I]:=2; end; For I:=3 to 5 do begin a[I]:=4; end; For I:=6 to 7 do begin a[I]:=1; end; For I:=8 to 9 do begin a[I]:=3; end; longar:=9; found:=0; intarray(a,longar); writeln(''); write('write the number you want to find: '); readln(num2); exist(a,num2,longar,found); if found=1 then writeln('found'); if found=0 then writeln('not found'); readln; end.
You have a couple of problems.
Your "display the array" routine (intarray) is perfect. Your "search the array" routine (exist) should look almost exactly like it. (But it doesn't).
The found variables should be boolean. Also, the found parameter should be a var parameter. The procedure type should be:
Frankly, I'd make it a function instead:
Also, a couple of suggestions:
It is OK to say just
At the bottom, use an if..else statement:
Hope this helps.
Your "display the array" routine (intarray) is perfect. Your "search the array" routine (exist) should look almost exactly like it. (But it doesn't).
The found variables should be boolean. Also, the found parameter should be a var parameter. The procedure type should be:
procedure exist (a: array of integer; longar, num2find: integer; var found: boolean);Frankly, I'd make it a function instead:
function exist (a: array of integer; longar, num2find: integer): boolean;Also, a couple of suggestions:
It is OK to say just
writeln;.At the bottom, use an if..else statement:
Pascal Syntax (Toggle Plain Text)
if found then writeln( 'Found' ) else writeln( 'Not Found );
Hope this helps.
![]() |
Similar Threads
- own programming language? (Computer Science)
Other Threads in the Pascal and Delphi Forum
- Previous Thread: Detect another application lost its focus.
- Next Thread: Problem regarding combo box components
| Thread Tools | Search this Thread |






