Pascal – Overview ”; Previous Next Pascal is a general-purpose, high-level language that was originally developed by Niklaus Wirth in the early 1970s. It was developed for teaching programming as a systematic discipline and to develop reliable and efficient programs. Pascal is Algol-based language and includes many constructs of Algol. Algol 60 is a subset of Pascal. Pascal offers several data types and programming structures. It is easy to understand and maintain the Pascal programs. Pascal has grown in popularity in the teaching and academics arena for various reasons: Easy to learn. Structured language. It produces transparent, efficient and reliable programs. It can be compiled on a variety of computer platforms. Features of the Pascal Language Pascal has the following features − Pascal is a strongly typed language. It offers extensive error checking. It offers several data types like arrays, records, files and sets. It offers a variety of programming structures. It supports structured programming through functions and procedures. It supports object oriented programming. Facts about Pascal The Pascal language was named for Blaise Pascal, French mathematician and pioneer in computer development. Niklaus Wirth completed development of the original Pascal programming language in 1970. Pascal is based on the block structured style of the Algol programming language. Pascal was developed as a language suitable for teaching programming as a systematic discipline, whose implementations could be both reliable and efficient. The ISO 7185 Pascal Standard was originally published in 1983. Pascal was the primary high-level language used for development in the Apple Lisa, and in the early years of the Mac. In 1986, Apple Computer released the first Object Pascal implementation, and in 1993, the Pascal Standards Committee published an Object-Oriented Extension to Pascal. Why to use Pascal? Pascal allows the programmers to define complex structured data types and build dynamic and recursive data structures, such as lists, trees and graphs. Pascal offers features like records, enumerations, subranges, dynamically allocated variables with associated pointers and sets. Pascal allows nested procedure definitions to any level of depth. This truly provides a great programming environment for learning programming as a systematic discipline based on the fundamental concepts. Among the most amazing implementations of Pascal are − Skype Total Commander TeX Macromedia Captivate Apple Lisa Various PC Games Embedded Systems Print Page Previous Next Advertisements ”;
Category: pascal
Pascal – Objects
Pascal – Object Oriented ”; Previous Next We can imagine our universe made of different objects like sun, earth, moon, etc. Similarly, we can imagine our car made of different objects like wheel, steering, gear, etc. Same way, there are object-oriented programming concepts, which assume everything as an object and implement a software using different objects. In Pascal, there are two structural data types used to implement a real world object − Object types Class types Object-Oriented Concepts Before we go in detail, let”s define important Pascal terms related to Object-Oriented Pascal. Object − An Object is a special kind of record that contains fields like a record; however, unlike records, objects contain procedures and functions as part of the object. These procedures and functions are held as pointers to the methods associated with the object”s type. Class − A Class is defined in almost the same way as an Object, but there is a difference in way they are created. The Class is allocated on the Heap of a program, whereas the Object is allocated on the Stack. It is a pointer to the object, not the object itself. Instantiation of a class − Instantiation means creating a variable of that class type. Since a class is just a pointer, when a variable of a class type is declared, there is memory allocated only for the pointer, not for the entire object. Only when it is instantiated using one of its constructors, memory is allocated for the object. Instances of a class are also called ”objects”, but do not confuse them with Object Pascal Objects. In this tutorial, we will write ”Object” for Pascal Objects and ”object” for the conceptual object or class instance. Member Variables − These are the variables defined inside a Class or an Object. Member Functions − These are the functions or procedures defined inside a Class or an Object and are used to access object data. Visibility of Members − The members of an Object or Class are also called the fields. These fields have different visibilities. Visibility refers to accessibility of the members, i.e., exactly where these members will be accessible. Objects have three visibility levels: public, private and protected. Classes have five visibility types: public, private, strictly private, protected and published. We will discuss visibility in details. Inheritance − When a Class is defined by inheriting existing functionalities of a parent Class, then it is said to be inherited. Here child class will inherit all or few member functions and variables of a parent class. Objects can also be inherited. Parent Class − A Class that is inherited by another Class. This is also called a base class or super class. Child Class − A class that inherits from another class. This is also called a subclass or derived class. Polymorphism − This is an object-oriented concept where same function can be used for different purposes. For example, function name will remain same but it may take different number of arguments and can do different tasks. Pascal classes implement polymorphism. Objects do not implement polymorphism. Overloading − It is a type of polymorphism in which some or all of operators have different implementations depending on the types of their arguments. Similarly functions can also be overloaded with different implementation. Pascal classes implement overloading, but the Objects do not. Data Abstraction − Any representation of data in which the implementation details are hidden (abstracted). Encapsulation − Refers to a concept where we encapsulate all the data and member functions together to form an object. Constructor − Refers to a special type of function which will be called automatically whenever there is an object formation from a class or an Object. Destructor − Refers to a special type of function which will be called automatically whenever an Object or Class is deleted or goes out of scope. Defining Pascal Objects An object is declared using the type declaration. The general form of an object declaration is as follows − type object-identifier = object private field1 : field-type; field2 : field-type; … public procedure proc1; function f1(): function-type; end; var objectvar : object-identifier; Let us define a Rectangle Object that has two integer type data members – length and width and some member functions to manipulate these data members and a procedure to draw the rectangle. type Rectangle = object private length, width: integer; public constructor init; destructor done; procedure setlength(l: inteter); function getlength(): integer; procedure setwidth(w: integer); function getwidth(): integer; procedure draw; end; var r1: Rectangle; pr1: ^Rectangle; After creating your objects, you will be able to call member functions related to that object. One member function will be able to process member variable of related object only. Following example shows how to set lengths and widths for two rectangle objects and draw them by calling the member functions. r1.setlength(3); r1.setwidth(7); writeln(” Draw a rectangle: ”, r1.getlength(), ” by ” , r1.getwidth()); r1.draw; new(pr1); pr1^.setlength(5); pr1^.setwidth(4); writeln(” Draw a rectangle: ”, pr1^.getlength(), ” by ” ,pr1^.getwidth()); pr1^.draw; dispose(pr1); Following is a complete example to show how to use objects in Pascal − Live Demo program exObjects; type Rectangle = object private length, width: integer; public procedure setlength(l: integer); function getlength(): integer; procedure setwidth(w: integer); function getwidth(): integer; procedure draw; end; var r1: Rectangle; pr1: ^Rectangle; procedure Rectangle.setlength(l: integer); begin length := l; end; procedure Rectangle.setwidth(w: integer); begin width :=w; end; function Rectangle.getlength(): integer; begin getlength := length; end; function Rectangle.getwidth(): integer; begin getwidth := width; end; procedure Rectangle.draw; var i, j: integer; begin for i:= 1 to length do begin for j:= 1 to width do write(” * ”); writeln; end; end; begin r1.setlength(3); r1.setwidth(7); writeln(”Draw a rectangle:”, r1.getlength(), ” by ” , r1.getwidth()); r1.draw; new(pr1); pr1^.setlength(5); pr1^.setwidth(4); writeln(”Draw a rectangle:”, pr1^.getlength(), ” by ” ,pr1^.getwidth()); pr1^.draw; dispose(pr1); end. When the above code is compiled and executed, it produces the following result − Draw a rectangle: 3 by 7 * * * * * * * * * * *
Pascal – Arrays
Pascal – Arrays ”; Previous Next Pascal programming language provides a data structure called the array, which can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. Instead of declaring individual variables, such as number1, number2, …, and number100, you declare one array variable such as numbers and use numbers[1], numbers[2], and …, numbers[100] to represent individual variables. A specific element in an array is accessed by an index. All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element. Please note that if you want a C style array starting from index 0, you just need to start the index from 0, instead of 1. Declaring Arrays To declare an array in Pascal, a programmer may either declare the type and then create variables of that array or directly declare the array variable. The general form of type declaration of one-dimensional array is − type array-identifier = array[index-type] of element-type; Where, array-identifier − indicates the name of the array type. index-type − specifies the subscript of the array; it can be any scalar data type except real element-type − specifies the types of values that are going to be stored For example, type vector = array [ 1..25] of real; var velocity: vector; Now, velocity is a variable array of vector type, which is sufficient to hold up to 25 real numbers. To start the array from 0 index, the declaration would be − type vector = array [ 0..24] of real; var velocity: vector; Types of Array Subscript In Pascal, an array subscript could be of any scalar type like, integer, Boolean, enumerated or subrange, except real. Array subscripts could have negative values too. For example, type temperature = array [-10 .. 50] of real; var day_temp, night_temp: temperature; Let us take up another example where the subscript is of character type − type ch_array = array[char] of 1..26; var alphabet: ch_array; Subscript could be of enumerated type − type color = ( red, black, blue, silver, beige); car_color = array of [color] of boolean; var car_body: car_color; Initializing Arrays In Pascal, arrays are initialized through assignment, either by specifying a particular subscript or using a for-do loop. For example − type ch_array = array[char] of 1..26; var alphabet: ch_array; c: char; begin … for c:= ”A” to ”Z” do alphabet[c] := ord[m]; (* the ord() function returns the ordinal values *) Accessing Array Elements An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example − a: integer; a: = alphabet[”A”]; The above statement will take the first element from the array named alphabet and assign the value to the variable a. Following is an example, which will use all the above-mentioned three concepts viz. declaration, assignment and accessing arrays − Live Demo program exArrays; var n: array [1..10] of integer; (* n is an array of 10 integers *) i, j: integer; begin (* initialize elements of array n to 0 *) for i := 1 to 10 do n[ i ] := i + 100; (* set element at location i to i + 100 *) (* output each array element”s value *) for j:= 1 to 10 do writeln(”Element[”, j, ”] = ”, n[j] ); end. When the above code is compiled and executed, it produces the following result − Element[1] = 101 Element[2] = 102 Element[3] = 103 Element[4] = 104 Element[5] = 105 Element[6] = 106 Element[7] = 107 Element[8] = 108 Element[9] = 109 Element[10] = 110 Pascal Arrays in Detail Arrays are important to Pascal and should need lots of more details. There are following few important concepts related to array which should be clear to a Pascal programmer − Sr.No Concept & Description 1 Multi-dimensional arrays Pascal supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array. 2 Dynamic array In this type of arrays, the initial length is zero. The actual length of the array must be set with the standard SetLength function. 3 Packed array These arrays are bit-packed, i.e., each character or truth values are stored in consecutive bytes instead of using one storage unit, usually a word (4 bytes or more). 4 Passing arrays to subprograms You can pass to a subprogram a pointer to an array by specifying the array”s name without an index. Print Page Previous Next Advertisements ”;
Pascal – Environment Setup
Pascal – Environment Set Up ”; Previous Next There are several Pascal compilers and interpreters available for general use. Among these are − Turbo Pascal − provides an IDE and compiler for running Pascal programs on CP/M, CP/M-86, DOS, Windows and Macintosh. Delphi − provides compilers for running Object Pascal and generates native code for 32- and 64-bit Windows operating systems, as well as 32-bit Mac OS X and iOS. Embarcadero is planning to build support for the Linux and Android operating system. Free Pascal − it is a free compiler for running Pascal and Object Pascal programs. Free Pascal compiler is a 32- and 64-bit Turbo Pascal and Delphi compatible Pascal compiler for Linux, Windows, OS/2, FreeBSD, Mac OS X, DOS and several other platforms. Turbo51 − It is a free Pascal compiler for the 8051 family of microcontrollers, with Turbo Pascal 7 syntax. Oxygene − It is an Object Pascal compiler for the .NET and Mono platforms. GNU Pascal (GPC) − It is a Pascal compiler composed of a front end to GNU Compiler Collection. We will be using Free Pascal in these tutorials. You can download Free Pascal for your operating system from the link: Download Free Pascal Installing Free Pascal on Linux The Linux distribution of Free Pascal comes in three forms − a tar.gz version, also available as separate files. a .rpm (Red Hat Package Manager) version. a .deb (Debian) version. Installation code for the .rpm version:: rpm -i fpc-X.Y.Z-N.ARCH.rpm Where X.Y.Z is the version number of the .rpm file, and ARCH is one of the supported architectures (i386, x86_64, etc.). Installation code for the Debian version (like Ubuntu): dpkg -i fpc-XXX.deb Where XXX is the version number of the .deb file. For details read: Free Pascal Installation Guide Installing Free Pascal on Mac If you use Mac OS X, the easiest way to use Free Pascal is to download the Xcode development environment from Apple”s web site and follow the simple installation instructions. Once you have Xcode setup, you will be able to use the Free Pascal compiler. Installing Free Pascal on Windows For Windows, you will download the Windows installer, setup.exe. This is a usual installation program. You need to take the following steps for installation − Select a directory. Select parts of the package you want to install. Optionally choose to associate the .pp or .pas extensions with the Free Pascal IDE. For details read: Free Pascal Installation Guide Text Editor This will be used to type your program. Examples of few editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi. Name and version of text editor can vary on different operating systems. For example, Notepad will be used on Windows and vim or vi can be used on windows as well as Linux or UNIX. The files you create with your editor are called source files and contain program source code. The source files for Pascal programs are typically named with the extension .pas. Before starting your programming, make sure you have one text editor in place and you have enough experience to write a computer program, save it in a file, compile it and finally execute it. Print Page Previous Next Advertisements ”;
Pascal – Loops
Pascal – Loops ”; Previous Next There may be a situation, when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. Programming languages provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages − Pascal programming language provides the following types of loop constructs to handle looping requirements. Click the following links to check their details. Sr.No Loop Type & Description 1 while-do loop Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. 2 for-do loop Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable. 3 repeat-until loop Like a while statement, except that it tests the condition at the end of the loop body. 4 nested loops You can use one or more loop inside any another while, for or repeat until loop. Loop Control Statements Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. Pascal supports the following control statements. Click the following links to check their details. Sr.No Control Statement & Description 1 break statement Terminates the loop or case statement and transfers execution to the statement immediately following the loop or case statement. 2 continue statement Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. 3 goto statement Transfers control to the labeled statement. Though it is not advised to use goto statement in your program. Print Page Previous Next Advertisements ”;
Pascal – Strings
Pascal – Strings ”; Previous Next The string in Pascal is actually a sequence of characters with an optional size specification. The characters could be numeric, letters, blank, special characters or a combination of all. Extended Pascal provides numerous types of string objects depending upon the system and implementation. We will discuss more common types of strings used in programs. You can define a string in many ways − Character arrays − This is a character string which is a sequence of zero or more byte-sized characters enclosed in single quotes. String variables − The variable of String type, as defined in Turbo Pascal. Short strings − The variable of String type with size specification. Null terminated strings − The variable of pchar type. AnsiStrings − Ansistrings are strings that have no length limit. Pascal provides only one string operator, string concatenation operator (+). Examples The following program prints first four kinds of strings. We will use AnsiStrings in the next example. program exString; var greetings: string; name: packed array [1..10] of char; organisation: string[10]; message: pchar; begin greetings := ”Hello ”; message := ”Good Day!”; writeln(”Please Enter your Name”); readln(name); writeln(”Please Enter the name of your Organisation”); readln(organisation); writeln(greetings, name, ” from ”, organisation); writeln(message); end. When the above code is compiled and executed, it produces the following result − Please Enter your Name John Smith Please Enter the name of your Organisation Infotech Hello John Smith from Infotech Following example makes use of few more functions, let”s see − Live Demo program exString; uses sysutils; var str1, str2, str3 : ansistring; str4: string; len: integer; begin str1 := ”Hello ”; str2 := ”There!”; (* copy str1 into str3 *) str3 := str1; writeln(”appendstr( str3, str1) : ”, str3 ); (* concatenates str1 and str2 *) appendstr( str1, str2); writeln( ”appendstr( str1, str2) ” , str1 ); str4 := str1 + str2; writeln(”Now str4 is: ”, str4); (* total lenghth of str4 after concatenation *) len := byte(str4[0]); writeln(”Length of the final string str4: ”, len); end. When the above code is compiled and executed, it produces the following result − appendstr( str3, str1) : Hello appendstr( str1, str2) : Hello There! Now str4 is: Hello There! There! Length of the final string str4: 18 Pascal String Functions and Procedures Pascal supports a wide range of functions and procedures that manipulate strings. These subprograms vary implement-wise. Here, we are listing various string manipulating subprograms provided by Free Pascal − Sr.No. Function & Purpose 1 function AnsiCompareStr(const S1: ; const S2:):Integer; Compares two strings 2 function AnsiCompareText(const S1: ; const S2:):Integer; Compares two strings, case insensitive 3 function AnsiExtractQuotedStr(var Src: PChar; Quote: Char):; Removes quotes from string 4 function AnsiLastChar(const S:):PChar; Gets last character of string 5 function AnsiLowerCase(const s:): Converts string to all-lowercase 6 function AnsiQuotedStr(const S: ; Quote: Char):; Quotes a string 7 function AnsiStrComp(S1: PChar;S2: PChar):Integer; Compares strings case-sensitive 8 function AnsiStrIComp(S1: PChar; S2: PChar):Integer; Compares strings case-insensitive 9 function AnsiStrLComp(S1: PChar; S2: PChar; MaxLen: Cardinal):Integer; Compares L characters of strings case sensitive 10 function AnsiStrLIComp(S1: PChar; S2: PChar; MaxLen: Cardinal):Integer; Compares L characters of strings case insensitive 11 function AnsiStrLastChar(Str: PChar):PChar; Gets last character of string 12 function AnsiStrLower(Str: PChar):PChar; Converts string to all-lowercase 13 function AnsiStrUpper(Str: PChar):PChar; Converts string to all-uppercase 14 function AnsiUpperCase(const s:):; Converts string to all-uppercase 15 procedure AppendStr(var Dest: ; const S:); Appends 2 strings 16 procedure AssignStr(var P: PString; const S:); Assigns value of strings on heap 17 function CompareStr(const S1: ; const S2:):Integer; overload; Compares two strings case sensitive 18 function CompareText(const S1: ; const S2:):Integer; Compares two strings case insensitive 19 procedure DisposeStr(S: PString); overload; Removes string from heap 20 procedure DisposeStr(S: PShortString); overload; Removes string from heap 21 function IsValidIdent( const Ident:):Boolean; Is string a valid pascal identifier 22 function LastDelimiter(const Delimiters: ; const S:):Integer; Last occurrence of character in a string 23 function LeftStr(const S: ; Count: Integer):; Gets first N characters of a string 24 function LoadStr(Ident: Integer):; Loads string from resources 25 function LowerCase(const s: ):; overload; Converts string to all-lowercase 26 function LowerCase(const V: variant ):; overload; Converts string to all-lowercase 27 function NewStr(const S:):PString; overload; Allocates new string on heap 28 function RightStr(const S: ; Count: Integer):; Gets last N characters of a string 29 function StrAlloc(Size: Cardinal):PChar; Allocates memory for string 30 function StrBufSize(Str: PChar):SizeUInt; Reserves memory for a string 31 procedure StrDispose(Str: PChar); Removes string from heap 32 function StrPas(Str: PChar):; Converts PChar to pascal string 33 function StrPCopy(Dest: PChar; Source:):PChar; Copies pascal string 34 function StrPLCopy(Dest: PChar; Source: ; MaxLen: SizeUInt):PChar; Copies N bytes of pascal string 35 function UpperCase(const s:):; Converts string to all-uppercase Print Page Previous Next Advertisements ”;
Pascal – Sets
Pascal – Sets ”; Previous Next A set is a collection of elements of same type. Pascal allows defining the set data type. The elements in a set are called its members. In mathematics, sets are represented by enclosing the members within braces{}. However, in Pascal, set elements are enclosed within square brackets [], which are referred as set constructor. Defining Set Types and Variables Pascal Set types are defined as type set-identifier = set of base type; Variables of set type are defined as var s1, s2, …: set-identifier; or, s1, s2…: set of base type; Examples of some valid set type declaration are − type Days = (mon, tue, wed, thu, fri, sat, sun); Letters = set of char; DaySet = set of days; Alphabets = set of ”A” .. ”Z”; studentAge = set of 13..20; Set Operators You can perform the following set operations on Pascal sets. Sr.No Operations & Descriptions 1 Union This joins two sets and gives a new set with members from both sets. 2 Difference Gets the difference of two sets and gives a new set with elements not common to either set. 3 Intersection Gets the intersection of two sets and gives a new set with elements common to both sets. 4 Inclusion A set P is included in set Q, if all items in P are also in Q but not vice versa. 5 Symmetric difference Gets the symmetric difference of two sets and gives a set of elements, which are in either of the sets and not in their intersection. 6 In It checks membership. Following table shows all the set operators supported by Free Pascal. Assume that S1 and S2 are two character sets, such that − S1 := [”a”, ”b”, ”c”]; S2 := [”c”, ”d”, ”e”]; Operator Description Example + Union of two sets S1 + S2 will give a set [”a”, ”b”, ”c”, ”d”, ”e”] – Difference of two sets S1 – S2 will give a set [”a”, ”b”] * Intersection of two sets S1 * S2 will give a set [”c”] >< Symmetric difference of two sets S1 >< S2 will give a set [”a”, ”b”, ”d”, ”e”] = Checks equality of two sets S1 = S2 will give the boolean value False <> Checks non-equality of two sets S1 <> S2 will give the boolean value True <= Contains (Checks if one set is a subset of the other) S1 <= S2 will give the boolean value False Include Includes an element in the set; basically it is the Union of a set and an element of same base type Include (S1, [”d”]) will give a set [”a”, ”b”, ”c”, ”d”] Exclude Excludes an element from a set; basically it is the Difference of a set and an element of same base type Exclude (S2, [”d”]) will give a set [”c”, ”e”] In Checks set membership of an element in a set [”e”] in S2 gives the boolean value True Example The following example illustrates the use of some of these operators − Live Demo program setColors; type color = (red, blue, yellow, green, white, black, orange); colors = set of color; procedure displayColors(c : colors); const names : array [color] of String[7] = (”red”, ”blue”, ”yellow”, ”green”, ”white”, ”black”, ”orange”); var cl : color; s : String; begin s:= ” ”; for cl:=red to orange do if cl in c then begin if (s<>” ”) then s :=s +” , ”; s:=s+names[cl]; end; writeln(”[”,s,”]”); end; var c : colors; begin c:= [red, blue, yellow, green, white, black, orange]; displayColors(c); c:=[red, blue]+[yellow, green]; displayColors(c); c:=[red, blue, yellow, green, white, black, orange] – [green, white]; displayColors(c); c:= [red, blue, yellow, green, white, black, orange]*[green, white]; displayColors(c); c:= [red, blue, yellow, green]><[yellow, green, white, black]; displayColors(c); end. When the above code is compiled and executed, it produces the following result − [ red , blue , yellow , green , white , black , orange] [ red , blue , yellow , green] [ red , blue , yellow , black , orange] [ green , white] [ red , blue , white , black] Print Page Previous Next Advertisements ”;
Pascal – Basic Syntax
Pascal – Basic Syntax ”; Previous Next You have seen a basic structure of pascal program, so it will be easy to understand other basic building blocks of the pascal programming language. Variables A variable definition is put in a block beginning with a var keyword, followed by definitions of the variables as follows: var A_Variable, B_Variable … : Variable_Type; Pascal variables are declared outside the code-body of the function which means they are not declared within the begin and end pairs, but they are declared after the definition of the procedure/function and before the begin keyword. For global variables, they are defined after the program header. Functions/Procedures In Pascal, a procedure is set of instructions to be executed, with no return value and a function is a procedure with a return value. The definition of function/procedures will be as follows − Function Func_Name(params…) : Return_Value; Procedure Proc_Name(params…); Comments The multiline comments are enclosed within curly brackets and asterisks as (* … *). Pascal allows single-line comment enclosed within curly brackets { … }. (* This is a multi-line comments and it will span multiple lines. *) { This is a single line comment in pascal } Case Sensitivity Pascal is a case non-sensitive language, which means you can write your variables, functions and procedure in either case. Like variables A_Variable, a_variable and A_VARIABLE have same meaning in Pascal. Pascal Statements Pascal programs are made of statements. Each statement specifies a definite job of the program. These jobs could be declaration, assignment, reading data, writing data, taking logical decisions, transferring program flow control, etc. For example − readln (a, b, c); s := (a + b + c)/2.0; area := sqrt(s * (s – a)*(s-b)*(s-c)); writeln(area); Reserved Words in Pascal The statements in Pascal are designed with some specific Pascal words, which are called the reserved words. For example, the words, program, input, output, var, real, begin, readline, writeline and end are all reserved words. Following is a list of reserved words available in Pascal. and array begin case const div do downto else end file for function goto if in label mod nil not of or packed procedure program record repeat set then to type until var while with Character set and Identifiers in Pascal The Pascal character set consists of − All upper case letters (A-Z) All lower case letters (a-z) All digits (0-9) Special symbols – + * / := , . ;. () [] = {} ` white space The entities in a Pascal program like variables and constants, types, functions, procedures and records, etc., have a name or identifier. An identifier is a sequence of letters and digits, beginning with a letter. Special symbols and blanks must not be used in an identifier. Print Page Previous Next Advertisements ”;
Pascal – Records
Pascal – Records ”; Previous Next Pascal arrays allow you to define type of variables that can hold several data items of the same kind but a record is another user-defined data type available in Pascal which allows you to combine data items of different kinds. Records consist of different fields. Suppose you want to keep track of your books in a library, you might want to track the following attributes about each book − Title Author Subject Book ID Defining a Record To define a record type, you may use the type declaration statement. The record type is defined as − type record-name = record field-1: field-type1; field-2: field-type2; … field-n: field-typen; end; Here is the way you would declare the Book record − type Books = record title: packed array [1..50] of char; author: packed array [1..50] of char; subject: packed array [1..100] of char; book_id: integer; end; The record variables are defined in the usual way as var r1, r2, … : record-name; Alternatively, you can directly define a record type variable as − var Books : record title: packed array [1..50] of char; author: packed array [1..50] of char; subject: packed array [1..100] of char; book_id: integer; end; Accessing Fields of a Record To access any field of a record, we use the member access operator (.). The member access operator is coded as a period between the record variable name and the field that we wish to access. Following is the example to explain usage of structure − Live Demo program exRecords; type Books = record title: packed array [1..50] of char; author: packed array [1..50] of char; subject: packed array [1..100] of char; book_id: longint; end; var Book1, Book2: Books; (* Declare Book1 and Book2 of type Books *) begin (* book 1 specification *) Book1.title := ”C Programming”; Book1.author := ”Nuha Ali ”; Book1.subject := ”C Programming Tutorial”; Book1.book_id := 6495407; (* book 2 specification *) Book2.title := ”Telecom Billing”; Book2.author := ”Zara Ali”; Book2.subject := ”Telecom Billing Tutorial”; Book2.book_id := 6495700; (* print Book1 info *) writeln (”Book 1 title : ”, Book1.title); writeln(”Book 1 author : ”, Book1.author); writeln( ”Book 1 subject : ”, Book1.subject); writeln( ”Book 1 book_id : ”, Book1.book_id); writeln; (* print Book2 info *) writeln (”Book 2 title : ”, Book2.title); writeln(”Book 2 author : ”, Book2.author); writeln( ”Book 2 subject : ”, Book2.subject); writeln( ”Book 2 book_id : ”, Book2.book_id); end. When the above code is compiled and executed, it produces the following result − Book 1 title : C Programming Book 1 author : Nuha Ali Book 1 subject : C Programming Tutorial Book 1 book_id : 6495407 Book 2 title : Telecom Billing Book 2 author : Zara Ali Book 2 subject : Telecom Billing Tutorial Book 2 book_id : 6495700 Records as Subprogram Arguments You can pass a record as a subprogram argument in very similar way as you pass any other variable or pointer. You would access the record fields in the similar way as you have accessed in the above example − Live Demo program exRecords; type Books = record title: packed array [1..50] of char; author: packed array [1..50] of char; subject: packed array [1..100] of char; book_id: longint; end; var Book1, Book2: Books; (* Declare Book1 and Book2 of type Books *) (* procedure declaration *) procedure printBook( var book: Books ); begin (* print Book info *) writeln (”Book title : ”, book.title); writeln(”Book author : ”, book.author); writeln( ”Book subject : ”, book.subject); writeln( ”Book book_id : ”, book.book_id); end; begin (* book 1 specification *) Book1.title := ”C Programming”; Book1.author := ”Nuha Ali ”; Book1.subject := ”C Programming Tutorial”; Book1.book_id := 6495407; (* book 2 specification *) Book2.title := ”Telecom Billing”; Book2.author := ”Zara Ali”; Book2.subject := ”Telecom Billing Tutorial”; Book2.book_id := 6495700; (* print Book1 info *) printbook(Book1); writeln; (* print Book2 info *) printbook(Book2); end. When the above code is compiled and executed, it produces the following result − Book 1 title : C Programming Book 1 author : Nuha Ali Book 1 subject : C Programming Tutorial Book 1 book_id : 6495407 Book 2 title : Telecom Billing Book 2 author : Zara Ali Book 2 subject : Telecom Billing Tutorial Book 2 book_id : 6495700 Pointers to Records You can define pointers to records in very similar way as you define pointer to any other variable as follows − type record-ptr = ^ record-name; record-name = record field-1: field-type1; field-2: field-type2; … field-n: field-typen; end; Now, you can store the address of a record type variable in the above-defined pointer variable. To declare a variable of the created pointer type, you use the var keyword − var r1, r2, … : record-ptr; Before using these pointers, you must create storage for a record-name type variable, which will be manipulated by these pointers. new(r1); new(r2); To access the members of a record using a pointer to that record, you must use the ^. operator as follows − r1^.feild1 := value1; r1^.feild2 := value2; … r1^fieldn := valuen; Finally, don”t forget to dispose the used storage, when it is no longer in use − dispose(r1); dispose(r2); Let us re-write the first example using a pointer to the Books record. Hope this will be easy for you to understand the concept − Live Demo program exRecords; type BooksPtr = ^ Books; Books = record title: packed array [1..50] of char; author: packed array [1..50] of char; subject: packed array [1..100] of char; book_id: longint; end; var (* Declare Book1 and Book2 of pointer type that refers to Book type *) Book1, Book2: BooksPtr; begin new(Book1); new(book2); (* book 1 specification *) Book1^.title := ”C Programming”; Book1^.author := ”Nuha Ali ”; Book1^.subject := ”C Programming Tutorial”; Book1^.book_id := 6495407; (* book 2 specification *) Book2^.title := ”Telecom Billing”; Book2^.author := ”Zara Ali”; Book2^.subject := ”Telecom Billing Tutorial”; Book2^.book_id := 6495700; (* print Book1 info *) writeln (”Book 1 title : ”, Book1^.title);
Pascal – Useful Resources
Pascal – Useful Resources ”; Previous Next The following resources contain additional information on Pascal. Please use them to get more in-depth knowledge on this topic. Useful Links on Pascal Free Pascal Compiler − The official website Open source Pascal compiler. Free pascal Documentation − A complete guide for Free Pascal programming. GNU Pascal − Home site of GNU Pascal, the free 32/64-bit Pascal compiler! GNU Pascal Manual − This manual documents how to run, install and maintain the GNU Pascal Compiler (GPC), as well as its new features and incompatibilities. Useful Books on Pascal To enlist your site on this page, please drop an email to [email protected] Print Page Previous Next Advertisements ”;