Jump to content

[PASCAL] Records


CouldnoT
 Share

Recommended Posts

Records

 

While arrays can hold many variables of the same type, records can hold variables of different types, and these variables are called 'Fields'.
This group of variables/fields can be treated as a single unit or variable. We can use records to store information that belong to the same object, for example, car information:

 

1. Car type: string variable
2. Engine size: real number
3. Production year: integer value
We can collect these different types in one record which represents a Car as in the following example:

 

program Cars;
{$mode objfpc}{$H+}
uses
 {$IFDEF UNIX}{$IFDEF UseCThreads}
 cthreads,
 {$ENDIF}{$ENDIF}
 Classes
 { you can add units after this };
type
 TCar = record
 ModelName: string;
 Engine: Single;
 ModelYear: Integer;
 end;
var
 Car: TCar;
begin
 Write('Input car Model Name: ');
 Readln(Car.ModelName);
 Write('Input car Engine size: ');
 Readln(Car.Engine);
 Write('Input car Model year: ');
 Readln(Car.ModelYear);
 Writeln;
 Writeln('Car information: ');
 Writeln('Model Name : ', Car.ModelName);
 Writeln('Engine size : ', Car.Engine);
 Writeln('Model Year : ', Car.ModelYear);
 Write('Press enter key to close..');
 Readln;
end.

 

In this example ,we have defined a new type (Record) using the 'type' keyword:

 

type
 TCar = record
 ModelName: string;
 Engine: Single;
 ModelYear: Integer;
 end;

 

We have added the letter (T) to Car to indicate that this is a type and not a variable. Variable names could be like: Car, Hour, UserName, but type names should be like: TCar, THouse, and TUserName. This is a standard in the Pascal language.

 

When we need to use this new type, then we should declare a variable of that type, for example:

 

var
 Car: TCar;

 

If we need to store a value in one of its variables/fields, we should access it like this:

 

 Car.ModelName

 

Edited by CouldnoT
Link to comment
Share on other sites

Guest
This topic is now closed to further replies.
 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.