Start New Discussion within our Software Development Community

I don't know why the next program doesn't find an element of the array.

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: [B]procedure[/B] exist (a: [B]array of integer[/B]; longar, num2find: [B]integer[/B]; [B]var[/B] found: [B]boolean[/B]); Frankly, I'd make it a function instead: [B]function[/B] exist (a: [B]array of integer[/B]; longar, num2find: [B]integer[/B]): [B]boolean[/B]; Also, a couple of suggestions:
It is OK to say just writeln; .

At the bottom, use an if..else statement:

if found
    then writeln( 'Found' )
    else writeln( 'Not Found );

Hope this helps.

This article has been dead for over six months. Start a new discussion instead.