Home > Back-end >  determine the number of arrays in the array of records using user-inputted variables in pascal
determine the number of arrays in the array of records using user-inputted variables in pascal

Time:11-09

I have a code written in Pascal. I have a record type called recordPembeli and I have an array[1..x] of recordPembeli. The x in this array will be the length of the data which is the user determine it in the body of program readln(x).

Here is the program:

program iniSesiDua;
uses crt;

type
    recordPembeli = record
        nama : string[5];
        jumlahPembelian : integer;
    end;

var
    x : integer
    dataPembelian : array[1..x] of recordPembeli;

begin
    clrscr;

    write('Masukkan jumlah pembeli : ');readln(x);

    readln;

end.

I try it and it says :

Warning: Variable "x" does not seem to be initialized
Error: Can't evaluate constant expression

Can I even determine the length of the data by user input in array of record or is it forbidden?

CodePudding user response:

The bounds of an array (unless it is a dynamic array) must be a compile time constant.

You are using a variable, and one that hasn't been initialized at that.

CodePudding user response:

Can I even determine the length of the data by user input in array of records...?

Yes you can, but the array must be dynamic, which means that the number of elements is not defined at compile time, but at run time:

var
  x: integer;
  dataPembelian: array of recordPembeli; // dynamic array, no size
  
begin
  write('Masukkan jumlah pembeli : ');readln(x); // Get length from user
  SetLength(dataPembelian, x);                   // create the records in the array

Note that the indexing of the array elements starts from 0.

CodePudding user response:

The variable determining the length x and the array’s declaration cannot be in the same block. You will need to use a nested block like this:

program iniSesiDua(input, output);
    type
        recordPembeli = record
                nama: string(5);
                jumlahPembelian: integer;
            end;
    
    var
        x: integer;
    
    procedure readAndProcessPembelin;
    var
        dataPembelian: array[1..x] of recordPembeli;
    begin
        { You read and process data here. }
    end;
    
    { === MAIN =============================================== }
    begin
        write('Masukkan jumlah pembeli : ');
        readLn(x);
        readAndProcessPembelin
    end.

Non-constant subrange bounds are an extension of ISO standard 10206 “Extended Pascal”. Your error messages seem like to have been emitted by the FPC (Free Pascal Compiler). This processor does not support Extended Pascal (yet). There you are forced to use an alternative data type, e. g. a linked list or more conveniently “dynamic” arrays.

  • Related