Delphi Pascal Programming

Delphi Pascal ProgrammingIn this One Video I completely cover the Delphi Programming language. I cover Data Types, Arrays, Conditionals, Looping, Casting, Functions, Procedures, Math, Records, Sets, Dates, Pointers, Custom Types, Recursion, Variants, File IO, Classes, Objects, Inheritance, Polymorphism and More!

All of the code follows below. Here is the Best Delphi Pascal Book. My Udemy Courses are 87.5% off till May 20th. Master Python and C++ today for just $9.99.

Code from the Video

Project 1

// The programs name is the same as the files name
// A Delphi app can have multiple units, but only 1 program file
program Project1;
// This is a comment
{ Multiline
Comment }
(* Another multiline
Comment *)
// Statements end with a ; and whitespace is ignored

// This is a compiler directive that defines this app runs in the console
{$APPTYPE CONSOLE}

// Includes an external resource file * uses the source files name
{$R *.res}

// Defines units we need for our program
uses
  SysUtils, Vcl.Dialogs, Character, Math;

// User defined data types
type

  // Create an array with indexes 1 through 10
  IntArray = array [1..10] of Integer;

  // A dynamic array with ability to change size
  DynArr = array of Integer;

  TGrades = 'A'..'E';
  // Enumerated Types have values starting with zero
  TDays = (Mon, Tue, Wed, Thu, Fri);

  // Set types are a group of values where a set can contain
  // multiples of those values defined
  TCard =(One,Two,Three,Four,Five,Six,Seven,Eight,Nine,Ten,J,Q,K,A);
  TCards = set of TCard;

// You can use var in multiple places in your program
//
// Variable names start with a letter or underscore
// They can contain letters, numbers and underscores
// The compiler is case insensitive for variable names
// MyVar is the same as myVar
// Variables are strongly typed
// You must cast variables if you want them to work together
var
  StrText: string;
  StrNum: string;
  // -2,147,483,648 to 2,147,483,647 (Same ad LongInt)
  Age: Integer;
  // 0 to 255 (Same as Byte and UInt8)
  Grade: Char;
  // True or False
  CanVote: Boolean;
  // 5.0E-324 to 1.7E308 (15 - 16 Significant digits) (Same as Real)
  Balance: Double;

  // -128 to 127 (Same as Int8)
  ChildTotal: ShortInt;
  // 0 to 65,535 (Same as WideChar and UInt16)
  Income: Word;
  // -32,768 to 32,767 (Same as Int16)
  Savings: SmallInt;
  // -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
  // Same as Comp
  DeficitTot: Int64;
  // -922,337,203,685,477.5808 to 922,337,203,685,477.5807
  DeficitChange: Currency;

  // User defined type
  MyArray: IntArray;
  DArray: DynArr;
  MultArray: array [0..3, 0..2] of Integer;

  // Used to cycle loops
  W, X, Y: Integer;

  // User defined type
  MyGrade: TGrades;
  FavDay: TDays;

  // Define a Set Type
  MyHand: TCards;
  OtherHand: TCards;
  ExtraHand: TCards;
  OneCard: TCard; // Will hold one card
  CardStr: string; // Used for card output
  CardArr : array [TCard] of String[14]
  = ('One','Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','J','Q','K','A');

  // Dates and Time
  NowTime: TDateTime;
  YY,MM,DD : Word;

  // Constant assignment for globals
  IAmGlobal: Integer = 10;
  // Define a constant (You can let the compiler define the type)
  const PI: Double = 3.14;

begin
  // Assignment operator :=
  StrText := 'Hello Pascal';
  Writeln(StrText);

  // Write('What is your name : ');
  // Get user input
  // readln(StrText);

  // Open dialog box
  // showmessage('Hello ' + StrText);

  // Bytes used for data type
  Writeln(Integer.Size.ToString);

  // ----- CASTING -----

  Age := 45;
  Writeln(Age.ToString);
  Writeln(Age.ToBoolean);
  Writeln(Age.ToDouble);
  CanVote := True;
  WriteLn(BoolToStr(CanVote, True));

  // Casting strings to numbers
  StrNum := '50';
  Writeln(StrToInt(StrNum));

// Chr : Converts number to character
// Trunc : Converts real into an integer
// StrToFloat : String to float
// FloatToStr : Float to string

  // ----- CHARACTER OPERATIONS -----
  Grade := 'A';
  Writeln(IsDigit(Grade));
  Writeln(IsLetter(Grade));
  Writeln(IsLower(Grade));
  Writeln(IsUpper(Grade));
  Writeln(IsWhiteSpace(Grade));
  Writeln(Chr(94)); // Get character with code
  Writeln(Ord('A')); // Get code for letter

  // ----- MATH -----

  Writeln('5 + 4 = ', 5+4);
  Writeln('5 - 4 = ', 5-4);
  Writeln('5 * 4 = ', 5*4);
  Writeln('5 / 4 = ', 5/4);
  Writeln('5 mod 4 = ', 5 mod 4);
  Writeln('5 div 4 = ', 5 div 4);

  Dec(Age); // Decrement
  Writeln('Age : ', Age);
  Inc(Age); // Increment
  Writeln('Age : ', Age);

  Writeln('Ceil 3.4 : ', Ceil(3.4));
  Writeln('Floor 3.4 : ', Floor(3.4));
  Writeln('Max 4, 5 : ', Max(4,5));
  Writeln('Min 4, 5 : ', Min(4,5));
  Writeln('Power 2^3 : ', Power(2,3));
  Writeln('Random 0,10 : ', RandomRange(0,10));
  // -1 if A<B, 0 if A=B, 1 if A>B
  Writeln('Compare 5, 4 : ', CompareValue(5,4));
  Writeln('45 deg to rads : ', degtorad(45));
  Writeln('3.14159 rads to degs : ', radtodeg(3.14159));
  // e * e * e ~= 20 so log(20.079) ~= 3
  Writeln('log(20.079) = ', lnxp1(20.079));
  // 2 * 2 * 2 = 8
  Writeln('log2(8) = ', log2(8));
  // 2 * 2 = 100
  Writeln('log10(100) = ', log10(100));
  // Hypotenuse : SQRT(A^2 + B^2)
  Writeln('hypot(2,3) = ', hypot(2,3));
  // Checks if the value is infinite
  Writeln('IsInfinite(5/0) = ', IsInfinite(5/0));
  // Checks if the value is infinite
  Writeln('IsZero(5/0) = ', IsZero(5/0));
  // Checks if the value is not a number
  Writeln('IsNan(5/0) = ', IsNan(5/0));

  // Trig functions work with radians
  // Cosecant, Secant, Cot, SinH, CosH, TanH,
  // ArcCos, ArcCosH, ArcSinH, ArcTan2, ArcTanH
  Writeln('Sin(0) = ', Sin(0));
  Writeln('Cos(Pi) = ', Cos(Pi));
  Writeln('Tan(Pi) = ', Tan(Pi));

  // ----- CONDITIONALS -----

  // Relational Operators : = <> < > <= >=
  // Logical Operators : and or not
  // Write('What is your age : ');
  // readln(Age);

  if ((Age >= 1) and (Age <= 18)) then
    Writeln('Important Birthday')

  else if ((Age = 21) or (Age = 50)) then
    Writeln('Important Birthday')

  else if (Age >= 65) then
    Writeln('Important Birthday')
  else
    Writeln('Not an Important Birthday');

  // Case
  Grade := 'B';
  case (Grade) of
      'A' : writeln('Awesome!' );
      'B', 'C': writeln('Do Better' );
      'D' : writeln('Terrible' );
      'F' : writeln('Failure' );
   end;

// You can also use ranges of values like this
// ā€˜a’..’z’: Which matches for any letter

  // ----- ARRAYS -----

  // Fixed size collection of data with the same type
  // Assign value using index
  MyArray[1] := 0;
  // Retrieve value from index
  Writeln('Array 0 : ', MyArray[1].ToString);

  // Set the size of the dynamic array
  setlength(DArray, 5);

  // ----- LOOPING -----

  // Initializing array
  for W := 1 to 5 do
    MyArray[W] := W;

  // Retrieving array values
  for W := 1 to 5 do
    Writeln('MyArray : ', MyArray[W]);

  // Initialize and display multidimensional array
  for W:= 1 to 3 do
      for X:= 1 to 2 do
         MultArray[W,X]:= W+X;

  for W:= 1 to 3 do
      for X:= 1 to 2 do
        Writeln(MultArray[W,X]);

  // Use a while loop to print odd values up to 13
  // Begin and End works like {} in C++ and contain multiple statements
  W := 1;
  while W <= 20 do
    begin
      if (W mod 2) = 0 then
        begin
          W := W + 1;
          continue;
        end;
      if W = 15 then
        break;

      Writeln('W : ', W);
      W := W + 1;
    end;

  // Use Repeat Until to create a guessing game
  W := RandomRange(0,10); // Number we try to guess
  X := 0; // Our guess
  Repeat
    Write('Guess the Number : ');
    Readln(X);
    if(X > W) then
      Writeln('To Big');
    if(X < W) then
      Writeln('To Small');
  Until W = X;
  Writeln('You Guessed It!');

  // ----- USER DEFINED TYPES -----
  MyGrade := 'A';
  Writeln('My Grade = ', MyGrade);
  FavDay := TDays.Fri;

  // ----- SETS -----

  // Set Types can contain multiple values
  MyHand := [Two, Four, J, Q, K];
  // You can add and subtract values
  MyHand := MyHand - [Two, Four] + [Ten, A];

  // You can get the union of 2 sets
  OtherHand := [Four, Two, Ten, J, A];
  ExtraHand := MyHand + OtherHand;

  // Get the difference
  ExtraHand := MyHand - OtherHand;

  // Get the intersection
  ExtraHand := MyHand * OtherHand;

  // Check equality and inequality
  Writeln(MyHand = OtherHand);
  Writeln(MyHand <> OtherHand);

  // Check if the set is a subset
  Writeln(MyHand <= OtherHand);

  // Check if value is in set
  Writeln(One in ExtraHand);

  // Cycle through all possible values defined for the set
  CardStr := '';
  for OneCard := One to A do
      // If the value is in ExtraHand
      if OneCard in ExtraHand then
      // Add it to the output string
      begin
         CardStr := CardStr + ' ';
         // Get the index and match it up to the string in CardArr
         CardStr := CardStr + CardArr[OneCard];
      end;
   writeln(CardStr);

   // ----- DATES -----

   NowTime := Now; // Gets current time
   Writeln('Current Time : ', TimeToStr(NowTime));
   Writeln('Current Date : ', DateToStr(NowTime));
   Writeln('Day : ', DayOfWeek(NowTime));
   Writeln('Current Date : ', DateToStr(NowTime));
   // Decode a date to year, month and day
   // Date returns the current date
   DecodeDate (Date,YY,MM,DD);
   // Encode year, month and day to a TDateTime value
   // You can define formating with FormatDateTime
   WriteLn ('Today is : ',FormatDateTime ('mmmm dd yyyy',EnCodeDate(YY,MM,DD)));

   // You could also format this way
   Writeln (Format ('Today is : %d/%d/%d ',[dd,mm,yy]));

  Readln;
end.

Project 2

program Project2;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  SysUtils, Vcl.Dialogs, Character, Math;

type

// This defines a record with music album info
Albums = record
   Title: String;
   Sold: Integer;
   Singer: String;
   LeadG: String;
   Drummer: String;
   AlbumID: longint;
end;

// Create pointers that point at addresses for different types
Iptr = ^Integer;
Dptr = ^Double;
Bptr = ^Boolean;
Aptr = ^Integer;
Arr = array[1..5] of Integer;

// These variables are global and can be used by any
// functions in the code
var
  W,X,Y: Integer;
  Result: Integer;

  // Declare album records
  Album1, Album2: Albums;

  // Assign pointers to these
  MyInt: Integer;
  MyDbl: Double;
  MyBool: Boolean;
  MyArr: Arr;

  // Declare pointer variables
  i_ptr: Iptr;
  d_ptr: Dptr;
  b_ptr: Bptr;
  a_ptr: Aptr;

  // Will hold a pointer for address
  ptrAdd: ^Word;

  // Declare strings
  str1, str2, str3 : ansistring;

  // Declare variant type
  MyVar: Variant;

  // Declare files with the type of data to store
  MyFile: TextFile;
  FileStr: String;

// Pascal has Procedures and Functions
// Procedures : Don't return a value but you can pass values by reference
// Functions : Do return a value
// The arguments are created when either begins execution
// and are destroyed after execution

// Define function name, parameters with types and return type
function GetSum(num1, num2: Integer): Integer;
begin
  // The value to return is assigned to the function name
  GetSum := num1 + num2;
end;

// Recursive functions call themselves
// They always have a condition that stops calling the function
function Factorial(num: Integer) : Integer;
begin
  if num <= 1 then
    Factorial := 1
  else
    Factorial := num * Factorial(num-1);

end;

procedure GetSum3(X, Y, Z: Integer; var Sum: Integer);
begin
   Sum := X+Y+Z;
end;

procedure PrintNum;
var
  // This version of W is local to PrintNum
  // Any changes made to it won't effect code outside the procedure
  W: Integer;

begin
  W := 1;
  Writeln('In PrintNum W = ', W);
end;

procedure AlbumSinger( var album1: Albums );
begin
   writeln('Singer : ', album1.Singer);
end;

// This function receives a pointer
function GetPtrVal(p: Iptr): Integer;
var
  val: Integer;
begin
  GetPtrVal := p^;
end;

begin
   W := 5;
   X := 4;

   Result := GetSum(W, X);
   Writeln('Sum : ', Result );

   Result := Factorial(4);
   Writeln('Factorial 4 : ', Result);
   // 1st : result = 4 * factorial(3) = 4 * 6 = 24
   // 2nd : result = 3 * factorial(2) = 3 * 2 = 6
   // 3rd : result = 2 * factorial(1) = 2 * 1 = 2

   // W will be assigned the value of Sum in the procedure
   GetSum3(1,2,3,W);
   Writeln('Sum : ', W);

   // Local and Global Variables
   W := 2;
   Writeln('Outside PrintNum W = ', W);
   PrintNum;
   Writeln('Outside PrintNum W = ', W);

   // ----- RECORDS -----
   // Arrays store lists of items with the same type with an index
   // Records define groups of different types referenced by name
   // They are like structs in other languages
   // Assign data
   Album1.Title := 'Smells Like Teen Spirit';
   Album1.Sold := 30000000;
   Album1.Singer := 'Kurt Cobain';
   Album1.LeadG := 'Kurt Cobain';
   Album1.Drummer := 'Dave Grohl';

   // Print Data
   Writeln('Albums Sold : ', Album1.Sold);

   // You can pass a record to a function or procedure
   AlbumSinger(Album1);

   // ----- POINTERS -----
   // Every variables value is stored in memory
   // Pointers store the address that holds the data assigned
   // to a variable
   MyInt := 10;
   MyDbl := 3.14;
   MyBool := False;
   for W := 1 to 5 do
     MyArr[W] := W;

   // Assign the address of the variable using the address operator
   i_ptr := @MyInt;
   d_ptr := @MyDbl;
   b_ptr := @MyBool;
   a_ptr := @MyArr;

   // Get the value with the dereference operator
   Writeln(i_ptr^);
   Writeln(d_ptr^);
   Writeln(b_ptr^);
   Writeln(a_ptr^);

   // Increment to the next array value
   Inc(a_ptr);
   Writeln(a_ptr^);

   // Decrement to the next array value
   Dec(a_ptr);
   Writeln(a_ptr^);

   // It is common to assign nill to a pointer variable
   ptrAdd := nil;

   // Print the address of the pointer if not nil
   ptrAdd := addr(i_ptr);
   if(ptrAdd <> nil) then
      Writeln(ptrAdd^);

   // Pass a pointer to a function for its value
   Writeln('Pointer Val : ', GetPtrVal(i_ptr));

   // ----- STRINGS -----
   str1 := 'Random ';
   str2 := 'Words';
   str3 := 'Words';

   // Concatenate strings
   Appendstr(str1, str2);
   Writeln(str1);

   // Get string length
   Writeln('Length : ', Length(str1));

   // Compare strings
   // Less than -1
   // Equal 0
   // Greater than 1
   // AnsiCompareText = Case insensitive
   Writeln(AnsiCompareStr(str3, str2));

   // Lowercase and uppercase is AnsiUpperCase
   Writeln(AnsiLowerCase(str1));

   // ----- VARIANTS -----
   // Varients are assigned their data type at run time
   // They can be any type other then containers
   MyVar := MyInt;
   MyVar := MyDbl;
   MyVar := MyBool;

   // ----- FILE IO -----
   // You can write any type of data to a file and retrieve it
   // I'll store text

   // Open a file for writing, write and close
   AssignFile(MyFile, 'myfile.txt');
   Rewrite(MyFile);
   Writeln(MyFile, 'Some Random Words');
   CloseFile(MyFile);

   // Open the file in read mode
   Reset(MyFile);

   // Cycle through lines until end of file, print and close
   while not Eof(MyFile) do
   begin
     Readln(MyFile, FileStr);
     Writeln(FileStr);
   end;
   CloseFile(MyFile);

   // Check if file exists
   if FileExists('myfile.txt') then
    Writeln('File Exists');

   DeleteFile('myfile.txt');
   if FileExists('myfile.txt') then
    Writeln('File Exists')
   else
    Writeln('File is Missing');

    // Get current directory
   Writeln('Directory : ', GetCurrentDir);

   // Create directory
   if CreateDir('SampDir') then
    Writeln('Directory Created');

   // Delete directory
   if RemoveDir('SampDir') then
    Writeln('Directory Deleted');

   Readln;
end.

Project 3

program Project3;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  SysUtils,
  Vcl.Dialogs,
  Character,
  Math;
  // Unit1 in 'Unit1.pas';

type
  // Define a shape class type
  // T is used for all classes
  TShape = class
    // Private data is not available to subclasses
    // Protected data is only accessable through
    // functions provided, but can be inherited by
    // subclasses
    protected
      Height, Width: Double;
    // Public data can be accessed by any code that has access
    // to the object
    public
      constructor Create;
      destructor Destroy; override;
      // You can overload functions so they perform different
      // actions based on different parameters
      Procedure SetValues(H, W: Double); overload;
      Procedure SetValues(W: Double); overload;
      // You can define this as virtual to figure out which
      // version of Area to call at runtime
      function Area: Double; virtual;
  end;

  // You can create a class that inherits everything from the
  // TShape class
  TCircle = class(TShape)
    public
      // We designate that we want to override Area
      // Final designates that we don't want inherited
      // subclasses of TCircle to be able to override
      // area
      function Area: Double; override; final;
  end;

// Called every time you create a new object
constructor TShape.Create;
begin
  Height := -1;
  Width := -1;
end;

// You can define that you want to destroy other objects
// that are part of this object here by calling Free
// on them
destructor TShape.Destroy;
begin

end;

// This will be used for shapes with height and width
procedure TShape.SetValues(H: Double; W: Double);
begin
  // Self allows you to refer to objects that you haven't
  // assigned a name to
  Self.Height := H;
  Self.Width := W;
end;

// This will be used for circles
procedure TShape.SetValues(W: Double);
begin
  // Self allows you to refer to objects that you haven't
  // assigned a name to
  Self.Height := -1;
  Self.Width := W;
end;

function TShape.Area: Double;
begin
  // Return area for circle if Height isn't provided
  if Height = -1 then
    Result := 3.14159 * Power(Self.Width/2, 2)
  else
    Result := Self.Height * Self.Width;
end;

function TCircle.Area: Double;
begin
  Result := 3.14159 * Power(Self.Width/2, 2)
end;

var
  MyShape: TShape;
  MyCircle: TShape;

  // With polymorphism you can declare as a TCircle or
  // as TShape and the correct Area function will still
  // be called
  // Circle2: TCircle;
  Circle2: TShape;

begin
  try
    // Create TShape object
    MyShape := TShape.Create;
    MyShape.SetValues(10, 10);
    Writeln('Area : ', MyShape.Area.ToString);

    // Delete object
    MyShape.Free;

    // Create a circle shape
    MyCircle := TShape.Create;
    MyCircle.SetValues(10);
    Writeln('Circle Area : ', MyCircle.Area.ToString);
    MyCircle.Free;

    // Inherited type TCircle
    Circle2 := TCircle.Create;
    Circle2.SetValues(5);
    Writeln('Circle 2 Area : ', Circle2.Area.ToString);
    Circle2.Free;

  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;

  Readln;
end.

Leave a Reply

Your email address will not be published. Required fields are marked *