Pascal – Quick Guide ”; Previous Next Pascal – Overview 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 Pascal – Environment Set Up 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. Pascal – Program Structures Before we study basic building blocks of the Pascal programming language, let us look a bare minimum Pascal program structure so that we can take it as a reference in upcoming chapters. Pascal Program Structure A Pascal program basically consists of the following parts − Program name Uses command Type declarations Constant declarations Variables declarations Functions declarations Procedures declarations Main program block Statements and Expressions within each block Comments Every pascal program generally has a heading statement, a declaration and an execution
Category: pascal
Pascal – Memory
Pascal – Memory Management ”; Previous Next This chapter explains dynamic memory management in Pascal. Pascal programming language provides several functions for memory allocation and management. Allocating Memory Dynamically While doing programming, if you are aware about the size of an array, then it is easy and you can define it as an array. For example, to store a name of any person, it can go max 100 characters so you can define something as follows − var name: array[1..100] of char; But now, let us consider a situation, where you have no idea about the length of the text you need to store, for example, you want to store a detailed description about a topic. Here, we need to define a pointer to string without defining how much memory is required. Pascal provides a procedure newto create pointer variables. program exMemory; var name: array[1..100] of char; description: ^string; begin name:= ”Zara Ali”; new(description); if not assigned(description) then writeln(” Error – unable to allocate required memory”) else description^ := ”Zara ali a DPS student in class 10th”; writeln(”Name = ”, name ); writeln(”Description: ”, description^ ); end. When the above code is compiled and executed, it produces the following result − Name = Zara Ali Description: Zara ali a DPS student in class 10th Now, if you need to define a pointer with specific number of bytes to be referred by it later, you should use the getmem function or the getmem procedure, which has the following syntax − procedure Getmem( out p: pointer; Size: PtrUInt ); function GetMem( size: PtrUInt ):pointer; In the previous example, we declared a pointer to a string. A string has a maximum value of 255 bytes. If you really don”t need that much space, or a larger space, in terms of bytes, getmem subprogram allows specifying that. Let us rewrite the previous example, using getmem − Live Demo program exMemory; var name: array[1..100] of char; description: ^string; begin name:= ”Zara Ali”; description := getmem(200); if not assigned(description) then writeln(” Error – unable to allocate required memory”) else description^ := ”Zara ali a DPS student in class 10th”; writeln(”Name = ”, name ); writeln(”Description: ”, description^ ); freemem(description); end. When the above code is compiled and executed, it produces the following result − Name = Zara Ali Description: Zara ali a DPS student in class 10th So, you have complete control and you can pass any size value while allocating memory unlike arrays, where once you defined the size cannot be changed. Resizing and Releasing Memory When your program comes out, operating system automatically releases all the memory allocated by your program, but as a good practice when you are not in need of memory anymore, then you should release that memory. Pascal provides the procedure dispose to free a dynamically created variable using the procedure new. If you have allocated memory using the getmem subprogram, then you need to use the subprogram freemem to free this memory. The freemem subprograms have the following syntax − procedure Freemem( p: pointer; Size: PtrUInt ); function Freemem( p: pointer ):PtrUInt; Alternatively, you can increase or decrease the size of an allocated memory block by calling the function ReAllocMem. Let us check the above program once again and make use of ReAllocMem and freemem subprograms. Following is the syntax for ReAllocMem − function ReAllocMem( var p: pointer; Size: PtrUInt ):pointer; Following is an example which makes use of ReAllocMem and freemem subprograms − Live Demo program exMemory; var name: array[1..100] of char; description: ^string; desp: string; begin name:= ”Zara Ali”; desp := ”Zara ali a DPS student.”; description := getmem(30); if not assigned(description) then writeln(”Error – unable to allocate required memory”) else description^ := desp; (* Suppose you want to store bigger description *) description := reallocmem(description, 100); desp := desp + ” She is in class 10th.”; description^:= desp; writeln(”Name = ”, name ); writeln(”Description: ”, description^ ); freemem(description); end. When the above code is compiled and executed, it produces the following result − Name = Zara Ali Description: Zara ali a DPS student. She is in class 10th Memory Management Functions Pascal provides a hoard of memory management functions that is used in implementing various data structures and implementing low-level programming in Pascal. Many of these functions are implementation dependent. Free Pascal provides the following functions and procedures for memory management − S.N Function Name & Description 1 function Addr(X: TAnytype):Pointer; Returns address of variable 2 function Assigned(P: Pointer):Boolean; Checks if a pointer is valid 3 function CompareByte(const buf1; const buf2; len: SizeInt):SizeInt; Compares 2 memory buffers byte per byte 4 function CompareChar(const buf1; const buf2; len: SizeInt):SizeInt; Compares 2 memory buffers byte per byte 5 function CompareDWord(const buf1; const buf2; len: SizeInt):SizeInt; Compares 2 memory buffers byte per byte 6 function CompareWord(const buf1; const buf2; len: SizeInt):SizeInt; Compares 2 memory buffers byte per byte 7 function Cseg: Word; Returns code segment 8 procedure Dispose(P: Pointer); Frees dynamically allocated memory 9 procedure Dispose(P: TypedPointer; Des: TProcedure); Frees dynamically allocated memory 10 function Dseg: Word; Returns data segment 11 procedure FillByte(var x; count: SizeInt; value: Byte); Fills memory region with 8-bit pattern 12 procedure FillChar( var x; count: SizeInt; Value: Byte|Boolean|Char); Fills memory region with certain character 13 procedure FillDWord( var x; count: SizeInt; value: DWord); Fills memory region with 32-bit pattern 14 procedure FillQWord( var x; count: SizeInt; value: QWord); Fills memory region with 64-bit pattern 15 procedure FillWord( var x; count: SizeInt; Value: Word); Fills memory region with 16-bit pattern 16 procedure Freemem( p: pointer; Size: PtrUInt); Releases allocated memory 17 procedure Freemem( p: pointer ); Releases allocated memory 18 procedure Getmem( out p: pointer; Size: PtrUInt); Allocates new memory 19 procedure Getmem( out p: pointer); Allocates new memory 20 procedure GetMemoryManager( var MemMgr: TMemoryManager); Returns current memory manager 21 function High( Arg: TypeOrVariable):TOrdinal; Returns highest index of open array or enumerated 22 function IndexByte( const buf; len: SizeInt; b: Byte):SizeInt; Finds byte-sized value in a memory range 23 function IndexChar(
Pascal – Classes
Pascal – Classes ”; Previous Next You have seen that Pascal Objects exhibit some characteristics of object-oriented paradigm. They implement encapsulation, data hiding and inheritance, but they also have limitations. For example, Pascal Objects do not take part in polymorphism. So classes are widely used to implement proper object-oriented behavior in a program, especially the GUI-based software. A Class is defined in almost the same way as an Object, but is a pointer to an Object rather than the Object itself. Technically, this means that the Class is allocated on the Heap of a program, whereas the Object is allocated on the Stack. In other words, when you declare a variable the object type, it will take up as much space on the stack as the size of the object, but when you declare a variable of the class type, it will always take the size of a pointer on the stack. The actual class data will be on the heap. Defining Pascal Classes A class is declared in the same way as an object, using the type declaration. The general form of a class declaration is as follows − type class-identifier = class private field1 : field-type; field2 : field-type; … public constructor create(); procedure proc1; function f1(): function-type; end; var classvar : class-identifier; Its worth to note following important points − Class definitions should come under the type declaration part of the program only. A class is defined using the class keyword. Fields are data items that exist in each instance of the class. Methods are declared within the definition of a class. There is a predefined constructor called Create in the Root class. Every abstract class and every concrete class is a descendant of Root, so all classes have at least one constructor. There is a predefined destructor called Destroy in the Root class. Every abstract class and every concrete class is a descendant of Root, so, all classes have at least one destructor. Let us define a Rectangle class 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 = class private length, width: integer; public constructor create(l, w: integer); procedure setlength(l: integer); function getlength(): integer; procedure setwidth(w: integer); function getwidth(): integer; procedure draw; end; Let us write a complete program that would create an instance of a rectangle class and draw the rectangle. This is the same example we used while discussing Pascal Objects. You will find both programs are almost same, with the following exceptions − You will need to include the {$mode objfpc} directive for using the classes. You will need to include the {$m+} directive for using constructors. Class instantiation is different than object instantiation. Only declaring the variable does not create space for the instance, you will use the constructor create to allocate memory. Here is the complete example − Live Demo {$mode objfpc} // directive to be used for defining classes {$m+} // directive to be used for using constructor program exClass; type Rectangle = class private length, width: integer; public constructor create(l, w: integer); procedure setlength(l: integer); function getlength(): integer; procedure setwidth(w: integer); function getwidth(): integer; procedure draw; end; var r1: Rectangle; constructor Rectangle.create(l, w: integer); begin length := l; width := w; end; 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:= Rectangle.create(3, 7); writeln(” Draw Rectangle: ”, r1.getlength(), ” by ” , r1.getwidth()); r1.draw; r1.setlength(4); r1.setwidth(6); writeln(” Draw Rectangle: ”, r1.getlength(), ” by ” , r1.getwidth()); r1.draw; end. When the above code is compiled and executed, it produces the following result − Draw Rectangle: 3 by 7 * * * * * * * * * * * * * * * * * * * * * Draw Rectangle: 4 by 6 * * * * * * * * * * * * * * * * * * * * * * * * Visibility of the Class Members Visibility indicates the accessibility of the class members. Pascal class members have five types of visibility − Sr.No Visibility & Accessibility 1 Public These members are always accessible. 2 Private These members can only be accessed in the module or unit that contains the class definition. They can be accessed from inside the class methods or from outside them. 3 Strict Private These members can only be accessed from methods of the class itself. Other classes or descendent classes in the same unit cannot access them. 4 Protected This is same as private, except, these members are accessible to descendent types, even if they are implemented in other modules. 5 Published This is same as a Public, but the compiler generates type information that is needed for automatic streaming of these classes if the compiler is in the {$M+} state. Fields defined in a published section must be of class type. Constructors and Destructors for Pascal Classes Constructors are special methods, which are called automatically whenever an object is created. So we take full advantage of this behavior by initializing many things through constructor functions. Pascal provides a special function called create() to define a constructor. You can pass as many arguments as you like into the constructor function. Following example will create one constructor for a class named Books and it will initialize price and title for the book at the time of object creation. Live Demo program classExample; {$MODE OBJFPC} //directive to be used for creating classes {$M+} //directive that allows class constructors and destructors type Books = Class private title : String; price: real; public constructor Create(t : String; p: real); //default constructor procedure setTitle(t : String); //sets title
Pascal – Procedures
Pascal – Procedures ”; Previous Next Procedures are subprograms that, instead of returning a single value, allow to obtain a group of results. Defining a Procedure In Pascal, a procedure is defined using the procedure keyword. The general form of a procedure definition is as follows − procedure name(argument(s): type1, argument(s): type 2, … ); < local declarations > begin < procedure body > end; A procedure definition in Pascal consists of a header, local declarations and a body of the procedure. The procedure header consists of the keyword procedure and a name given to the procedure. Here are all the parts of a procedure − Arguments − The argument(s) establish the linkage between the calling program and the procedure identifiers and also called the formal parameters. Rules for arguments in procedures are same as that for the functions. Local declarations − Local declarations refer to the declarations for labels, constants, variables, functions and procedures, which are applicable to the body of the procedure only. Procedure Body − The procedure body contains a collection of statements that define what the procedure does. It should always be enclosed between the reserved words begin and end. It is the part of a procedure where all computations are done. Following is the source code for a procedure called findMin(). This procedure takes 4 parameters x, y, z and m and stores the minimum among the first three variables in the variable named m. The variable m is passed by reference (we will discuss passing arguments by reference a little later) − procedure findMin(x, y, z: integer; var m: integer); (* Finds the minimum of the 3 values *) begin if x < y then m := x else m := y; if z <m then m := z; end; { end of procedure findMin } Procedure Declarations A procedure declaration tells the compiler about a procedure name and how to call the procedure. The actual body of the procedure can be defined separately. A procedure declaration has the following syntax − procedure name(argument(s): type1, argument(s): type 2, … ); Please note that the name of the procedure is not associated with any type. For the above defined procedure findMin(), following is the declaration − procedure findMin(x, y, z: integer; var m: integer); Calling a Procedure While creating a procedure, you give a definition of what the procedure has to do. To use the procedure, you will have to call that procedure to perform the defined task. When a program calls a procedure, program control is transferred to the called procedure. A called procedure performs the defined task, and when its last end statement is reached, it returns the control back to the calling program. To call a procedure, you simply need to pass the required parameters along with the procedure name as shown below − program exProcedure; var a, b, c, min: integer; procedure findMin(x, y, z: integer; var m: integer); (* Finds the minimum of the 3 values *) begin if x < y then m:= x else m:= y; if z < m then m:= z; end; { end of procedure findMin } begin writeln(” Enter three numbers: ”); readln( a, b, c); findMin(a, b, c, min); (* Procedure call *) writeln(” Minimum: ”, min); end. When the above code is compiled and executed, it produces the following result − Enter three numbers: 89 45 67 Minimum: 45 Recursive Subprograms We have seen that a program or subprogram may call another subprogram. When a subprogram calls itself, it is referred to as a recursive call and the process is known as recursion. To illustrate the concept, let us calculate the factorial of a number. Factorial of a number n is defined as − n! = n*(n-1)! = n*(n-1)*(n-2)! … = n*(n-1)*(n-2)*(n-3)… 1 The following program calculates the factorial of a given number by calling itself recursively. program exRecursion; var num, f: integer; function fact(x: integer): integer; (* calculates factorial of x – x! *) begin if x=0 then fact := 1 else fact := x * fact(x-1); (* recursive call *) end; { end of function fact} begin writeln(” Enter a number: ”); readln(num); f := fact(num); writeln(” Factorial ”, num, ” is: ” , f); end. When the above code is compiled and executed, it produces the following result − Enter a number: 5 Factorial 5 is: 120 Following is another example, which generates the Fibonacci Series for a given number using a recursive function − Live Demo program recursiveFibonacci; var i: integer; function fibonacci(n: integer): integer; begin if n=1 then fibonacci := 0 else if n=2 then fibonacci := 1 else fibonacci := fibonacci(n-1) + fibonacci(n-2); end; begin for i:= 1 to 10 do write(fibonacci (i), ” ”); end. When the above code is compiled and executed, it produces the following result − 0 1 1 2 3 5 8 13 21 34 Arguments of a Subprogram If a subprogram (function or procedure) is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the subprogram. The formal parameters behave like other local variables inside the subprogram and are created upon entry into the subprogram and destroyed upon exit. While calling a subprogram, there are two ways that arguments can be passed to the subprogram − Sr.No Call Type & Description 1 Call by value This method copies the actual value of an argument into the formal parameter of the subprogram. In this case, changes made to the parameter inside the subprogram have no effect on the argument. 2 Call by reference This method copies the address of an argument into the formal parameter. Inside the subprogram, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument. By default, Pascal uses call by value to pass arguments. In general, this means that code within a subprogram cannot alter the
Pascal – Data Types
Pascal – Data Types ”; Previous Next Data types of an entity indicates the meaning, constraints, possible values, operations, functions and mode of storage associated with it. Integer, real, Boolean and character types are referred as standard data types. Data types can be categorized as scalar, pointer and structured data types. Examples of scalar data types are integer, real, Boolean, character, subrange and enumerated. Structured data types are made of the scalar types; for example, arrays, records, files and sets. We will discuss the pointer data types later. Pascal Data Types Pascal data types can be summarized as below in the following diagram − Type Declarations The type declaration is used to declare the data type of an identifier. Syntax of type declaration is − type-identifier-1, type-identfier-2 = type-specifier; For example, the following declaration defines the variables days and age as integer type, yes and true as Boolean type, name and city as string type, fees and expenses as real type. type days, age = integer; yes, true = boolean; name, city = string; fees, expenses = real; Integer Types Following table gives you details about standard integer types with its storage sizes and value ranges used in Object Pascal − Type Minimum Maximum Format Integer -2147483648 2147483647 signed 32-bit Cardinal 0 4294967295 unsigned 32-bit Shortint -128 127 signed 8-bit Smallint -32768 32767 signed 16-bit Longint -2147483648 2147483647 signed 32-bit Int64 -2^63 2^63 – 1 signed 64-bit Byte 0 255 unsigned 8-bit Word 0 65535 unsigned 16-bit Longword 0 4294967295 unsigned 32-bit Constants Use of constants makes a program more readable and helps to keep special quantities at one place in the beginning of the program. Pascal allows numerical, logical, string and character constants. Constants can be declared in the declaration part of the program by specifying the const declaration. Syntax of constant type declaration is follows − const Identifier = contant_value; Following are some examples of constant declarations − VELOCITY_LIGHT = 3.0E=10; PIE = 3.141592; NAME = ”Stuart Little”; CHOICE = yes; OPERATOR = ”+”; All constant declarations must be given before the variable declaration. Enumerated types Enumerated data types are user-defined data types. They allow values to be specified in a list. Only assignment operators and relational operators are permitted on enumerated data type. Enumerated data types can be declared as follows − type enum-identifier = (item1, item2, item3, … ) Following are some examples of enumerated type declarations − type SUMMER = (April, May, June, July, September); COLORS = (Red, Green, Blue, Yellow, Magenta, Cyan, Black, White); TRANSPORT = (Bus, Train, Airplane, Ship); The order in which the items are listed in the domain of an enumerated type defines the order of the items. For example, in the enumerated type SUMMER, April comes before May, May comes before June, and so on. The domain of enumerated type identifiers cannot consist of numeric or character constants. Subrange Types Subrange types allow a variable to assume values that lie within a certain range. For example, if the age of voters should lie between 18 to 100 years, a variable named age could be declared as − var age: 18 … 100; We will look at variable declaration in detail in the next section. You can also define a subrange type using the type declaration. Syntax for declaring a subrange type is as follows − type subrange-identifier = lower-limit … upper-limit; Following are some examples of subrange type declarations − const P = 18; Q = 90; type Number = 1 … 100; Value = P … Q; Subrange types can be created from a subset of an already defined enumerated type, For example − type months = (Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec); Summer = Apr … Aug; Winter = Oct … Dec; Print Page Previous Next Advertisements ”;
Pascal – Variable Scope
Pascal – Variable Scope ”; Previous Next A scope in any programming is a region of the program where a defined variable can have its existence and beyond that variable cannot be accessed. There are three places, where variables can be declared in Pascal programming language − Inside a subprogram or a block which is called local variables Outside of all subprograms which is called global variables In the definition of subprogram parameters which is called formal parameters Let us explain what are local and global variables and formal parameters. Local Variables Variables that are declared inside a subprogram or block are called local variables. They can be used only by statements that are inside that subprogram or block of code. Local variables are not known to subprograms outside their own. Following is the example using local variables. Here, all the variables a, b and c are local to program named exLocal. Live Demo program exLocal; var a, b, c: integer; begin (* actual initialization *) a := 10; b := 20; c := a + b; writeln(”value of a = ”, a , ” b = ”, b, ” and c = ”, c); end. When the above code is compiled and executed, it produces the following result − value of a = 10 b = 20 c = 30 Now, let us extend the program little more, let us create a procedure named display, which will have its own set of variables a, b and c and display their values, right from the program exLocal. Live Demo program exLocal; var a, b, c: integer; procedure display; var a, b, c: integer; begin (* local variables *) a := 10; b := 20; c := a + b; writeln(”Winthin the procedure display”); writeln(”value of a = ”, a , ” b = ”, b, ” and c = ”, c); end; begin a:= 100; b:= 200; c:= a + b; writeln(”Winthin the program exlocal”); writeln(”value of a = ”, a , ” b = ”, b, ” and c = ”, c); display(); end. When the above code is compiled and executed, it produces the following result − Within the program exlocal value of a = 100 b = 200 c = 300 Within the procedure display value of a = 10 b = 20 c = 30 Global Variables Global variables are defined outside of a function, usually on top of the program. The global variables will hold their value throughout the lifetime of your program and they can be accessed inside any of the functions defined for the program. A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its declaration. Following is an example using global and local variables − Live Demo program exGlobal; var a, b, c: integer; procedure display; var x, y, z: integer; begin (* local variables *) x := 10; y := 20; z := x + y; (*global variables *) a := 30; b:= 40; c:= a + b; writeln(”Winthin the procedure display”); writeln(” Displaying the global variables a, b, and c”); writeln(”value of a = ”, a , ” b = ”, b, ” and c = ”, c); writeln(”Displaying the local variables x, y, and z”); writeln(”value of x = ”, x , ” y = ”, y, ” and z = ”, z); end; begin a:= 100; b:= 200; c:= 300; writeln(”Winthin the program exlocal”); writeln(”value of a = ”, a , ” b = ”, b, ” and c = ”, c); display(); end. When the above code is compiled and executed, it produces the following result − Within the program exlocal value of a = 100 b = 200 c = 300 Within the procedure display Displaying the global variables a, b, and c value of a = 30 b = 40 c = 70 Displaying the local variables x, y, and z value of x = 10 y = 20 z = 30 Please note that the procedure display has access to the variables a, b and c, which are global variables with respect to display as well as its own local variables. A program can have same name for local and global variables but value of local variable inside a function will take preference. Let us change the previous example a little, now the local variables for the procedure display has same names as a, b, c − Live Demo program exGlobal; var a, b, c: integer; procedure display; var a, b, c: integer; begin (* local variables *) a := 10; b := 20; c := a + b; writeln(”Winthin the procedure display”); writeln(” Displaying the global variables a, b, and c”); writeln(”value of a = ”, a , ” b = ”, b, ” and c = ”, c); writeln(”Displaying the local variables a, b, and c”); writeln(”value of a = ”, a , ” b = ”, b, ” and c = ”, c); end; begin a:= 100; b:= 200; c:= 300; writeln(”Winthin the program exlocal”); writeln(”value of a = ”, a , ” b = ”, b, ” and c = ”, c); display(); end. When the above code is compiled and executed, it produces the following result − Within the program exlocal value of a = 100 b = 200 c = 300 Within the procedure display Displaying the global variables a, b, and c value of a = 10 b = 20 c = 30 Displaying the local variables a, b, and c value of a = 10 b = 20 c = 30 Print Page Previous Next Advertisements ”;
Pascal – Constants
Pascal – Constants ”; Previous Next A constant is an entity that remains unchanged during program execution. Pascal allows only constants of the following types to be declared − Ordinal types Set types Pointer types (but the only allowed value is Nil). Real types Char String Declaring Constants Syntax for declaring constants is as follows − const identifier = constant_value; The following table provides examples of some valid constant declarations − Sr.No Constant Type & Examples 1 Ordinal(Integer)type constant valid_age = 21; 2 Set type constant Vowels = set of (A,E,I,O,U); 3 Pointer type constant P = NIL; 4 Real type constant e = 2.7182818; velocity_light = 3.0E+10; 5 Character type constant Operator = ”+”; 6 String type constant president = ”Johnny Depp”; The following example illustrates the concept − program const_circle (input,output); const PI = 3.141592654; var r, d, c : real; {variable declaration: radius, dia, circumference} begin writeln(”Enter the radius of the circle”); readln(r); d := 2 * r; c := PI * d; writeln(”The circumference of the circle is ”,c:7:2); end. When the above code is compiled and executed, it produces the following result − Enter the radius of the circle 23 The circumference of the circle is 144.51 Observe the formatting in the output statement of the program. The variable c is to be formatted with total number of digits 7 and 2 digits after the decimal sign. Pascal allows such output formatting with the numerical variables. Print Page Previous Next Advertisements ”;
Pascal – Booleans
Pascal – Booleans ”; Previous Next Pascal provides data type Boolean that enables the programmers to define, store and manipulate logical entities, such as constants, variables, functions and expressions, etc. Boolean values are basically integer type. Boolean type variables have two pre-defined possible values True and False. The expressions resolving to a Boolean value can also be assigned to a Boolean type. Free Pascal also supports the ByteBool, WordBool and LongBool types. These are of type Byte, Word or Longint, respectively. The value False is equivalent to 0 (zero) and any nonzero value is considered True when converting to a Boolean value. A Boolean value of True is converted to -1 in case it is assigned to a variable of type LongBool. It should be noted that logical operators and, or and not are defined for Boolean data types. Declaration of Boolean Data Types A variable of Boolean type is declared using the var keyword. var boolean-identifier: boolean; for example, var choice: boolean; Example Live Demo program exBoolean; var exit: boolean; choice: char; begin writeln(”Do you want to continue? ”); writeln(”Enter Y/y for yes, and N/n for no”); readln(choice); if(choice = ”n”) then exit := true else exit := false; if (exit) then writeln(” Good Bye!”) else writeln(”Please Continue”); readln; end. When the above code is compiled and executed, it produces the following result − Do you want to continue? Enter Y/y for yes, and N/n for no N Good Bye! Y Please Continue Print Page Previous Next Advertisements ”;
Pascal – Variable Types
Pascal – Variable Types ”; Previous Next A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in Pascal has a specific type, which determines the size and layout of the variable”s memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable. The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Pascal is not case-sensitive, so uppercase and lowercase letters mean same here. Based on the basic types explained in previous chapter, there will be following basic variable types − Basic Variables in Pascal Sr.No Type & Description 1 Character Typically a single octet (one byte). This is an integer type. 2 Integer The most natural size of integer for the machine. 3 Real A single-precision floating point value. 4 Boolean Specifies true or false logical values. This is also an integer type. 5 Enumerated Specifies a user-defined list. 6 Subrange Represents variables, whose values lie within a range. 7 String Stores an array of characters. Pascal programming language also allows defining various other types of variables, which we will cover in subsequent chapters like Pointer, Array, Records, Sets, and Files, etc. For this chapter, let us study only basic variable types. Variable Declaration in Pascal All variables must be declared before we use them in Pascal program. All variable declarations are followed by the var keyword. A declaration specifies a list of variables, followed by a colon (:) and the type. Syntax of variable declaration is − var variable_list : type; Here, type must be a valid Pascal data type including character, integer, real, boolean, or any user-defined data type, etc., and variable_list may consist of one or more identifier names separated by commas. Some valid variable declarations are shown here − var age, weekdays : integer; taxrate, net_income: real; choice, isready: boolean; initials, grade: char; name, surname : string; In the previous tutorial, we have discussed that Pascal allows declaring a type. A type can be identified by a name or identifier. This type can be used to define variables of that type. For example, type days, age = integer; yes, true = boolean; name, city = string; fees, expenses = real; Now, the types so defined can be used in variable declarations − var weekdays, holidays : days; choice: yes; student_name, emp_name : name; capital: city; cost: expenses; Please note the difference between type declaration and var declaration. Type declaration indicates the category or class of the types such as integer, real, etc., whereas the variable specification indicates the type of values a variable may take. You can compare type declaration in Pascal with typedef in C. Most importantly, the variable name refers to the memory location where the value of the variable is going to be stored. This is not so with the type declaration. Variable Initialization in Pascal Variables are assigned a value with a colon and the equal sign, followed by a constant expression. The general form of assigning a value is − variable_name := value; By default, variables in Pascal are not initialized with zero. They may contain rubbish values. So it is a better practice to initialize variables in a program. Variables can be initialized (assigned an initial value) in their declaration. The initialization is followed by the var keyword and the syntax of initialization is as follows − var variable_name : type = value; Some examples are − age: integer = 15; taxrate: real = 0.5; grade: char = ”A”; name: string = ”John Smith”; Let us look at an example, which makes use of various types of variables discussed so far − Live Demo program Greetings; const message = ” Welcome to the world of Pascal ”; type name = string; var firstname, surname: name; begin writeln(”Please enter your first name: ”); readln(firstname); writeln(”Please enter your surname: ”); readln(surname); writeln; writeln(message, ” ”, firstname, ” ”, surname); end. When the above code is compiled and executed, it produces the following result − Please enter your first name: John Please enter your surname: Smith Welcome to the world of Pascal John Smith Enumerated Variables You have seen how to use simple variable types like integer, real and boolean. Now, let”s see variables of enumerated type, which can be defined as − var var1, var2, … : enum-identifier; When you have declared an enumerated type, you can declare variables of that type. For example, type months = (January, February, March, April, May, June, July, August, September, October, November, December); Var m: months; … M := January; The following example illustrates the concept − Live Demo program exEnumeration; type beverage = (coffee, tea, milk, water, coke, limejuice); var drink:beverage; begin writeln(”Which drink do you want?”); drink := limejuice; writeln(”You can drink ”, drink); end. When the above code is compiled and executed, it produces the following result − Which drink do you want? You can drink limejuice Subrange Variables Subrange variables are declared as − var subrange-name : lowerlim … uperlim; Examples of subrange variables are − var marks: 1 … 100; grade: ”A” … ”E”; age: 1 … 25; The following program illustrates the concept − Live Demo program exSubrange; var marks: 1 .. 100; grade: ”A” .. ”E”; begin writeln( ”Enter your marks(1 – 100): ”); readln(marks); writeln( ”Enter your grade(A – E): ”); readln(grade); writeln(”Marks: ” , marks, ” Grade: ”, grade); end. When the above code is compiled and executed, it produces the following result − Enter your marks(1 – 100): 100 Enter your grade(A – E): A Marks: 100 Grade: A Print Page Previous Next Advertisements ”;
Pascal – Units
Pascal – Units ”; Previous Next A Pascal program can consist of modules called units. A unit might consist of some code blocks, which in turn are made up of variables and type declarations, statements, procedures, etc. There are many built-in units in Pascal and Pascal allows programmers to define and write their own units to be used later in various programs. Using Built-in Units Both the built-in units and user-defined units are included in a program by the uses clause. We have already used the variants unit in Pascal – Variants tutorial. This tutorial explains creating and including user-defined units. However, let us first see how to include a built-in unit crt in your program − program myprog; uses crt; The following example illustrates using the crt unit − Program Calculate_Area (input, output); uses crt; var a, b, c, s, area: real; begin textbackground(white); (* gives a white background *) clrscr; (*clears the screen *) textcolor(green); (* text color is green *) gotoxy(30, 4); (* takes the pointer to the 4th line and 30th column) writeln(”This program calculates area of a triangle:”); writeln(”Area = area = sqrt(s(s-a)(s-b)(s-c))”); writeln(”S stands for semi-perimeter”); writeln(”a, b, c are sides of the triangle”); writeln(”Press any key when you are ready”); readkey; clrscr; gotoxy(20,3); write(”Enter a: ”); readln(a); gotoxy(20,5); write(”Enter b:”); readln(b); gotoxy(20, 7); write(”Enter c: ”); readln(c); s := (a + b + c)/2.0; area := sqrt(s * (s – a)*(s-b)*(s-c)); gotoxy(20, 9); writeln(”Area: ”,area:10:3); readkey; end. It is the same program we used right at the beginning of the Pascal tutorial, compile and run it to find the effects of the change. Creating and Using a Pascal Unit To create a unit, you need to write the modules or subprograms you want to store in it and save it in a file with .pas extension. The first line of this file should start with the keyword unit followed by the name of the unit. For example − unit calculateArea; Following are three important steps in creating a Pascal unit − The name of the file and the name of the unit should be exactly same. So, our unit calculateArea will be saved in a file named calculateArea.pas. The next line should consist of a single keyword interface. After this line, you will write the declarations for all the functions and procedures that will come in this unit. Right after the function declarations, write the word implementation, which is again a keyword. After the line containing the keyword implementation, provide definition of all the subprograms. The following program creates the unit named calculateArea − unit CalculateArea; interface function RectangleArea( length, width: real): real; function CircleArea(radius: real) : real; function TriangleArea( side1, side2, side3: real): real; implementation function RectangleArea( length, width: real): real; begin RectangleArea := length * width; end; function CircleArea(radius: real) : real; const PI = 3.14159; begin CircleArea := PI * radius * radius; end; function TriangleArea( side1, side2, side3: real): real; var s, area: real; begin s := (side1 + side2 + side3)/2.0; area := sqrt(s * (s – side1)*(s-side2)*(s-side3)); TriangleArea := area; end; end. Next, let us write a simple program that would use the unit we defined above − program AreaCalculation; uses CalculateArea,crt; var l, w, r, a, b, c, area: real; begin clrscr; l := 5.4; w := 4.7; area := RectangleArea(l, w); writeln(”Area of Rectangle 5.4 x 4.7 is: ”, area:7:3); r:= 7.0; area:= CircleArea(r); writeln(”Area of Circle with radius 7.0 is: ”, area:7:3); a := 3.0; b:= 4.0; c:= 5.0; area:= TriangleArea(a, b, c); writeln(”Area of Triangle 3.0 by 4.0 by 5.0 is: ”, area:7:3); end. When the above code is compiled and executed, it produces the following result − Area of Rectangle 5.4 x 4.7 is: 25.380 Area of Circle with radius 7.0 is: 153.938 Area of Triangle 3.0 by 4.0 by 5.0 is: 6.000 Print Page Previous Next Advertisements ”;