How can I identify the mistake in my Pascal Code?

115 Views Asked by At

Here's the code, I don't think that there's a mistake in Read1d Procedure but each time I execute this program it displays that the value of all the elements of the array is 0. Where is my mistake?

Program MainProgram;
Uses Crt;

Const
  n = 100;

Type
  TypeIn = 1..n;
  Array1d = Array[TypeIn] Of Integer;

Procedure Read1d(Var Tai: TypeIn; X: Array1d);
Var
  i: TypeIn;
Begin
  Writeln('Enter the size of the array: ');
  Readln(Tai);
  For i := 1 To Tai Do
  Begin
    Write('X[', i, '] = ');
    Read(X[i]);
  End;
End;

Procedure Write1d(Var Tai: TypeIn; X: Array1d);
Var
  i: TypeIn;
Begin
  Write(' | ');
  For i := 1 To Tai Do
  Begin
    Write(X[i], ' | ');
  End;
  WriteLn;
End;

Function Nbev(Tai:TypeIn; X: Array1d ; V:Integer):Integer;
var i, cpt:Integer;
Begin
  cpt := 0;
  for i := 1 to tai do
  Begin
    if X[i] = V then 
      cpt := cpt + 1; 
  End;
  Nbev := cpt;
End;

Function RechV(Tai: TypeIn; X: Array1d; V: Integer): Boolean;
Var
  i: TypeIn; //Result: Boolean;
Begin
  Result := False;
  For i := 1 To Tai Do
  Begin
    If X[i] = V Then
    Begin
      Result := True;
      Break;
    End;
  End;
  RechV := Result;
End;

Var
  Tai: TypeIn;

  X: Array1d;
  V: Integer;

Begin
  textcolor(green);
  textbackground(black);
  ClrScr;
  Read1d(Tai, X);
  WriteLn;
  Write1d(Tai, X);
  Writeln('What''s the element you are looking for: ');
  Readln(V);

  If RechV(Tai, X, V) Then
  Begin
    Writeln('Element found.');
    WriteLn(Nbev(Tai, X, V));
  End
  Else
    Writeln('Element not found.');
End.

I was trying to input values for each element of the Array1d Array, Write all the elements down and then Give the solution that allows to find a given value V in an array of at most 100 integers. The following test will explain my situation.

I expected this:

Enter the size of the array:
4
X[1] = 1
X[2] = 2
X[3] = 3
X[4] = 4

 | 1 | 2 | 3 | 4 |
What's the element you are looking for:
4
Element found.

I got this :

Enter the size of the array:
4
X[1] = 1
X[2] = 2
X[3] = 3
X[4] = 4

 | 0 | 0 | 0 | 0 |
What's the element you are looking for:
4
Element not found.

What should I do to fix it?

1

There are 1 best solutions below

1
MBo On

Make argument "by reference"

Procedure Read1d(Var Tai: TypeIn; var X: Array1d);

Otherwise your procedure makes a copy of array because it is argument "by value", and you fill local copy of array instead of global instance