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 ”;

Pascal – Variants

Pascal – Variants ”; Previous Next Pascal supports a unique type of storage named variants. You can assign any simple type of values in a variant variable. The type of a value stored in a variant is only determined at runtime. Almost any simple type can be assigned to variants: ordinal types, string types, int64 types. Structured types such as sets, records, arrays, files, objects and classes are not assignment-compatible with a variant. You can also assign a pointer to a variant. Free Pascal supports variants. Declaring a Variant You can declare variant type like any other types using the var keyword. The syntax for declaring a variant type is − var v: variant; Now, this variant variable v can be assigned to almost all simple types including the enumerated types and vice versa. type color = (red, black, white); var v : variant; i : integer; b : byte; w : word; q : int64; e : extended; d : double; en : color; as : ansistring; ws : widestring; begin v := i; v := b; v := w; v := q; v := e; v := en; v := d: v := as; v := ws; end; Example The following example would illustrate the concept − Live Demo Program exVariant; uses variants; type color = (red, black, white); var v : variant; i : integer; r: real; c : color; as : ansistring; begin i := 100; v:= i; writeln(”Variant as Integer: ”, v); r:= 234.345; v:= r; writeln(”Variant as real: ”, v); c := red; v := c; writeln(”Variant as Enumerated data: ”, v); as:= ” I am an AnsiString”; v:= as; writeln(”Variant as AnsiString: ”, v); end. When the above code is compiled and executed, it produces the following result − Variant as Integer: 100 Variant as real: 234.345 Variant as Enumerated data: 0 Variant as AnsiString: I am an AnsiString Print Page Previous Next Advertisements ”;

Pascal – Pointers

Pascal – Pointers ”; Previous Next Pointers in Pascal are easy and fun to learn. Some Pascal programming tasks are performed more easily with pointers, and other tasks, such as dynamic memory allocation, cannot be performed without using pointers. So it becomes necessary to learn pointers to become a perfect Pascal programmer. Let”s start learning them in simple and easy steps. As you know, every variable is a memory location and every memory location has its address defined which can be accessed using the name of the pointer variable, which denotes an address in memory. What Are Pointers? A pointer is a dynamic variable, whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before you can use it to store any variable address. The general form of a pointer variable declaration is − type ptr-identifier = ^base-variable-type; The pointer type is defined by prefixing the up-arrow of caret symbol (^) with the base type. The base-type defines the types of the data items. Once a pointer variable is defined to be of certain type, it can point data items of that type only. Once a pointer type has been defined, we can use the var declaration to declare pointer variables. var p1, p2, … : ptr-identifier; Following are some valid pointer declarations − type Rptr = ^real; Cptr = ^char; Bptr = ^ Boolean; Aptr = ^array[1..5] of real; date-ptr = ^ date; Date = record Day: 1..31; Month: 1..12; Year: 1900..3000; End; var a, b : Rptr; d: date-ptr; The pointer variables are dereferenced by using the same caret symbol (^). For example, the associated variable referred by a pointer rptr, is rptr^. It can be accessed as − rptr^ := 234.56; The following example will illustrate this concept − Live Demo program exPointers; var number: integer; iptr: ^integer; begin number := 100; writeln(”Number is: ”, number); iptr := @number; writeln(”iptr points to a value: ”, iptr^); iptr^ := 200; writeln(”Number is: ”, number); writeln(”iptr points to a value: ”, iptr^); end. When the above code is compiled and executed, it produces the following result − Number is: 100 iptr points to a value: 100 Number is: 200 iptr points to a value: 200 Printing a Memory Address in Pascal In Pascal, we can assign the address of a variable to a pointer variable using the address operator (@). We use this pointer to manipulate and access the data item. However, if for some reason, we need to work with the memory address itself, we need to store it in a word type variable. Let us extend the above example to print the memory address stored in the pointer iptr − Live Demo program exPointers; var number: integer; iptr: ^integer; y: ^word; begin number := 100; writeln(”Number is: ”, number); iptr := @number; writeln(”iptr points to a value: ”, iptr^); iptr^ := 200; writeln(”Number is: ”, number); writeln(”iptr points to a value: ”, iptr^); y := addr(iptr); writeln(y^); end. When the above code is compiled and executed, it produces the following result − Number is: 100 iptr points to a value: 100 Number is: 200 iptr points to a value: 200 45504 NIL Pointers It is always a good practice to assign a NIL value to a pointer variable in case you do not have exact address to be assigned. This is done at the time of variable declaration. A pointer that is assigned NIL points to nowhere. Consider the following program − Live Demo program exPointers; var number: integer; iptr: ^integer; y: ^word; begin iptr := nil; y := addr(iptr); writeln(”the vaule of iptr is ”, y^); end. When the above code is compiled and executed, it produces the following result − The value of ptr is 0 To check for a nil pointer you can use an if statement as follows − if(ptr <> nill )then (* succeeds if p is not null *) if(ptr = nill)then (* succeeds if p is null *) Pascal Pointers in Detail Pointers have many but easy concepts and they are very important to Pascal programming. There are following few important pointer concepts, which should be clear to a Pascal programmer − Sr.No Concept & Description 1 Pascal – Pointer arithmetic There are four arithmetic operators that can be used on pointers: increment,decrement, +, – 2 Pascal – Array of pointers You can define arrays to hold a number of pointers. 3 Pascal – Pointer to pointer Pascal allows you to have pointer on a pointer and so on. 4 Passing pointers to subprograms in Pascal Passing an argument by reference or by address both enable the passed argument to be changed in the calling subprogram by the called subprogram. 5 Return pointer from subprograms in Pascal Pascal allows a subprogram to return a pointer. Print Page Previous Next Advertisements ”;

Pascal – Operators

Pascal – Operators ”; Previous Next An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. Pascal allows the following types of operators − Arithmetic operators Relational operators Boolean operators Bit operators Set operators String operators Let us discuss the arithmetic, relational, Boolean and bit operators one by one. We will discuss the set operators and string operations later. Arithmetic Operators Following table shows all the arithmetic operators supported by Pascal. Assume variable A holds 10 and variable B holds 20, then − Show Examples Operator Description Example + Adds two operands A + B will give 30 – Subtracts second operand from the first A – B will give -10 * Multiplies both operands A * B will give 200 / Divides numerator by denominator B / A will give 2 % Modulus Operator and remainder of after an integer division B % A will give 0 Relational Operators Following table shows all the relational operators supported by Pascal. Assume variable A holds 10 and variable B holds 20, then − Show Examples Operator Description Example = Checks if the values of two operands are equal or not, if yes, then condition becomes true. (A = B) is not true. <> Checks if the values of two operands are equal or not, if values are not equal, then condition becomes true. (A <> B) is true. > Checks if the value of left operand is greater than the value of right operand, if yes, then condition becomes true. (A > B) is not true. < Checks if the value of left operand is less than the value of right operand, if yes, then condition becomes true. (A < B) is true. >= Checks if the value of left operand is greater than or equal to the value of right operand, if yes, then condition becomes true. (A >= B) is not true. <= Checks if the value of left operand is less than or equal to the value of right operand, if yes, then condition becomes true. (A <= B) is true. Boolean Operators Following table shows all the Boolean operators supported by Pascal language. All these operators work on Boolean operands and produce Boolean results. Assume variable A holds true and variable B holds false, then − Show Examples Operator Description Example and Called Boolean AND operator. If both the operands are true, then condition becomes true. (A and B) is false. and then It is similar to the AND operator, however, it guarantees the order in which the compiler evaluates the logical expression. Left to right and the right operands are evaluated only when necessary. (A and then B) is false. or Called Boolean OR Operator. If any of the two operands is true, then condition becomes true. (A or B) is true. or else It is similar to Boolean OR, however, it guarantees the order in which the compiler evaluates the logical expression. Left to right and the right operands are evaluated only when necessary. (A or else B) is true. not Called Boolean NOT Operator. Used to reverse the logical state of its operand. If a condition is true, then Logical NOT operator will make it false. not (A and B) is true. Bit Operators Bitwise operators work on bits and perform bit-by-bit operation. All these operators work on integer operands and produces integer results. The truth table for bitwise and (&), bitwise or (|), and bitwise not (~) are as follows − p q p & q p | q ~p ~q 0 0 0 0 1 1 0 1 0 1 1 0 1 1 1 1 0 0 1 0 0 1 0 1 Assume if A = 60; and B = 13; now in binary format they will be as follows − A = 0011 1100 B = 0000 1101 —————– A&B = 0000 1100 A^B = 0011 0001 ~A  = 1100 0011 The Bitwise operators supported by Pascal are listed in the following table. Assume variable A holds 60 and variable B holds 13, then: Show Examples Operator Description Example & Binary AND Operator copies a bit to the result if it exists in both operands. (A & B) will give 12, which is 0000 1100 | Binary OR Operator copies a bit if it exists in either operand. (A | B) will give 61, which is 0011 1101 ! Binary OR Operator copies a bit if it exists in either operand. Its same as | operator. (A ! B) will give 61, which is 0011 1101 ~ Binary Ones Complement Operator is unary and has the effect of ”flipping” bits. (~A ) will give -61, which is 1100 0011 in 2”s complement form due to a signed binary number. << Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. A << 2 will give 240, which is 1111 0000 >> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. A >> 2 will give 15, which is 0000 1111 Please note that different implementations of Pascal differ in bitwise operators. Free Pascal, the compiler we used here, however, supports the following bitwise operators − Operators Operations not Bitwise NOT and Bitwise AND or Bitwise OR xor Bitwise exclusive OR shl Bitwise shift left shr Bitwise shift right << Bitwise shift left >> Bitwise shift right Operators Precedence in Pascal Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator. For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7. Here, operators with the

Pascal – File Handling

Pascal – File Handling ”; Previous Next Pascal treats a file as a sequence of components, which must be of uniform type. A file”s type is determined by the type of the components. File data type is defined as − type file-name = file of base-type; Where, the base-type indicates the type of the components of the file. The base type could be anything like, integer, real, Boolean, enumerated, subrange, record, arrays and sets except another file type. Variables of a file type are created using the var declaration − var f1, f2,…: file-name; Following are some examples of defining some file types and file variables − type rfile = file of real; ifile = file of integer; bfile = file of boolean; datafile = file of record arrfile = file of array[1..4] of integer; var marks: arrfile; studentdata: datafile; rainfalldata: rfile; tempdata: ifile; choices: bfile; Creating and Writing to a File Let us write a program that would create a data file for students” records. It would create a file named students.dat and write a student”s data into it − program DataFiles; type StudentRecord = Record s_name: String; s_addr: String; s_batchcode: String; end; var Student: StudentRecord; f: file of StudentRecord; begin Assign(f,”students.dat”); Rewrite(f); Student.s_name := ”John Smith”; Student.s_addr := ”United States of America”; Student.s_batchcode := ”Computer Science”; Write(f,Student); Close(f); end. When compiled and run, the program would create a file named students.dat into the working directory. You can open the file using a text editor, like notepad, to look at John Smith”s data. Reading from a File We have just created and written into a file named students.dat. Now, let us write a program that would read the student”s data from the file − program DataFiles; type StudentRecord = Record s_name: String; s_addr: String; s_batchcode: String; end; var Student: StudentRecord; f: file of StudentRecord; begin assign(f, ”students.dat”); reset(f); while not eof(f) do begin read(f,Student); writeln(”Name: ”,Student.s_name); writeln(”Address: ”,Student.s_addr); writeln(”Batch Code: ”, Student.s_batchcode); end; close(f); end. When the above code is compiled and executed, it produces the following result − Name: John Smith Address: United States of America Batch Code: Computer Science Files as Subprogram Parameter Pascal allows file variables to be used as parameters in standard and user-defined subprograms. The following example illustrates this concept. The program creates a file named rainfall.txt and stores some rainfall data. Next, it opens the file, reads the data and computes the average rainfall. Please note that, if you use a file parameter with subprograms, it must be declared as a var parameter. program addFiledata; const MAX = 4; type raindata = file of real; var rainfile: raindata; filename: string; procedure writedata(var f: raindata); var data: real; i: integer; begin rewrite(f, sizeof(data)); for i:=1 to MAX do begin writeln(”Enter rainfall data: ”); readln(data); write(f, data); end; close(f); end; procedure computeAverage(var x: raindata); var d, sum: real; average: real; begin reset(x); sum:= 0.0; while not eof(x) do begin read(x, d); sum := sum + d; end; average := sum/MAX; close(x); writeln(”Average Rainfall: ”, average:7:2); end; begin writeln(”Enter the File Name: ”); readln(filename); assign(rainfile, filename); writedata(rainfile); computeAverage(rainfile); end. When the above code is compiled and executed, it produces the following result − Enter the File Name: rainfall.txt Enter rainfall data: 34 Enter rainfall data: 45 Enter rainfall data: 56 Enter rainfall data: 78 Average Rainfall: 53.25 Text Files A text file, in Pascal, consists of lines of characters where each line is terminated with an end-of-line marker. You can declare and define such files as − type file-name = text; Difference between a normal file of characters and a text file is that a text file is divided into lines, each terminated by a special end-of-line marker, automatically inserted by the system. The following example creates and writes into a text file named contact.txt − program exText; var filename, data: string; myfile: text; begin writeln(”Enter the file name: ”); readln(filename); assign(myfile, filename); rewrite(myfile); writeln(myfile, ”Note to Students: ”); writeln(myfile, ”For details information on Pascal Programming”); writeln(myfile, ”Contact: Tutorials Point”); writeln(”Completed writing”); close(myfile); end. When the above code is compiled and executed, it produces the following result − Enter the file name: contact.txt Completed writing Appending to a File Appending to a file means writing to an existing file that already has some data without overwriting the file. The following program illustrates this − program exAppendfile; var myfile: text; info: string; begin assign(myfile, ”contact.txt”); append(myfile); writeln(”Contact Details”); writeln(”[email protected]”); close(myfile); (* let us read from this file *) assign(myfile, ”contact.txt”); reset(myfile); while not eof(myfile) do begin readln(myfile, info); writeln(info); end; close(myfile); end. When the above code is compiled and executed, it produces the following result − Contact Details [email protected] Note to Students: For details information on Pascal Programming Contact: Tutorials Point File Handling Functions Free Pascal provides the following functions/procedures for file handling − Sr.No. Function Name & Description 1 procedure Append(var t: Text); Opens a file in append mode 2 procedure Assign(out f: file; const Name:); Assigns a name to a file 3 procedure Assign(out f: file; p: PChar); Assigns a name to a file 4 procedure Assign(out f: file; c: Char); Assigns a name to a file 5 procedure Assign(out f: TypedFile; const Name:); Assigns a name to a file 6 procedure Assign(out f: TypedFile; p: PChar); Assigns a name to a file 7 procedure Assign(out f: TypedFile; c: Char); Assigns a name to a file 8 procedure Assign(out t: Text; const s:); Assigns a name to a file 9 procedure Assign(out t: Text; p: PChar); Assigns a name to a file 10 procedure Assign(out t: Text; c: Char); Assigns a name to a file 11 procedure BlockRead(var f: file; var Buf; count: Int64; var Result: Int64); Reads data from a file into memory 12 procedure BlockRead(var f: file; var Buf; count: LongInt; var Result: LongInt); Reads data from a file into memory 13 procedure BlockRead(var f: file; var Buf; count: Cardinal; var Result: Cardinal); Reads data from a file into memory 14 procedure BlockRead(var f: file; var Buf; count: Word;

Pascal – Date & Time

Pascal – Date and Time ”; Previous Next Most of the softwares you write need implementing some form of date functions returning current date and time. Dates are so much part of everyday life that it becomes easy to work with them without thinking. Pascal also provides powerful tools for date arithmetic that makes manipulating dates easy. However, the actual name and workings of these functions are different for different compilers. Getting the Current Date & Time Pascal”s TimeToString function gives you the current time in a colon(: ) delimited form. The following example shows how to get the current time − Live Demo program TimeDemo; uses sysutils; begin writeln (”Current time : ”,TimeToStr(Time)); end. When the above code was compiled and executed, it produces the following result − Current time : 18:33:08 The Date function returns the current date in TDateTime format. The TDateTime is a double value, which needs some decoding and formatting. The following program demonstrates how to use it in your program to display the current date − Program DateDemo; uses sysutils; var YY,MM,DD : Word; begin writeln (”Date : ”,Date); DeCodeDate (Date,YY,MM,DD); writeln (format (”Today is (DD/MM/YY): %d/%d/%d ”,[dd,mm,yy])); end. When the above code was compiled and executed, it produces the following result − Date: 4.111300000000000E+004 Today is (DD/MM/YY):23/7/2012 The Now function returns the current date and time − Live Demo Program DatenTimeDemo; uses sysutils; begin writeln (”Date and Time at the time of writing : ”,DateTimeToStr(Now)); end. When the above code was compiled and executed, it produces the following result − Date and Time at the time of writing : 23/7/2012 18:51: Free Pascal provides a simple time stamp structure named TTimeStamp, which has the following format − type TTimeStamp = record Time: Integer; Date: Integer; end; Various Date & Time Functions Free Pascal provides the following date and time functions − Sr.No. Function Name & Description 1 function DateTimeToFileDate(DateTime: TDateTime):LongInt; Converts DateTime type to file date. 2 function DateTimeToStr( DateTime: TDateTime):; Constructs string representation of DateTime 3 function DateTimeToStr(DateTime: TDateTime; const FormatSettings: TFormatSettings):; Constructs string representation of DateTime 4 procedure DateTimeToString(out Result: ;const FormatStr: ;const DateTime: TDateTime); Constructs string representation of DateTime 5 procedure DateTimeToString(out Result: ; const FormatStr: ; const DateTime: TDateTime; const FormatSettings: TFormatSettings); Constructs string representation of DateTime 6 procedure DateTimeToSystemTime(DateTime: TDateTime; out SystemTime: TSystemTime); Converts DateTime to system time 7 function DateTimeToTimeStamp( DateTime: TDateTime):TTimeStamp;Converts DateTime to timestamp 8 function DateToStr(Date: TDateTime):; Constructs string representation of date 9 function DateToStr(Date: TDateTime; const FormatSettings: TFormatSettings):; Constructs string representation of date 10 function Date: TDateTime; Gets current date 11 function DayOfWeek(DateTime: TDateTime):Integer; Gets day of week 12 procedure DecodeDate(Date: TDateTime; out Year: Word; out Month: Word; out Day: Word); Decodes DateTime to year month and day 13 procedure DecodeTime(Time: TDateTime; out Hour: Word; out Minute: Word; out Second: Word; out MilliSecond: Word); Decodes DateTime to hours, minutes and seconds 14 function EncodeDate(Year: Word; Month: Word; Day: Word):TDateTime; Encodes year, day and month to DateTime 15 function EncodeTime(Hour: Word; Minute: Word; Second: Word; MilliSecond: Word):TDateTime; Encodes hours, minutes and seconds to DateTime 16 function FormatDateTime(const FormatStr: ; DateTime: TDateTime):; Returns string representation of DateTime 17 function FormatDateTime(const FormatStr: ; DateTime: TDateTime; const FormatSettings: TFormatSettings):; Returns string representation of DateTime 18 function IncMonth(const DateTime: TDateTime; NumberOfMonths: Integer = 1):TDateTime; Adds 1 to month 19 function IsLeapYear(Year: Word):Boolean; Determines if year is leap year 20 function MSecsToTimeStamp(MSecs: Comp):TTimeStamp; Converts number of milliseconds to timestamp 21 function Now: TDateTime; Gets current date and time 22 function StrToDateTime(const S:):TDateTime; Converts string to DateTime 23 function StrToDateTime(const s: ShortString; const FormatSettings: TFormatSettings):TDateTime; Converts string to DateTime 24 function StrToDateTime(const s: AnsiString; const FormatSettings: TFormatSettings):TDateTime; Converts string to DateTime 25 function StrToDate(const S: ShortString):TDateTime; Converts string to date 26 function StrToDate(const S: Ansistring):TDateTime; Converts string to date 27 function StrToDate(const S: ShortString; separator: Char):TDateTime; Converts string to date 28 function StrToDate(const S: AnsiString; separator: Char):TDateTime; Converts string to date 29 function StrToDate(const S: ShortString; const useformat: ; separator: Char):TDateTime; Converts string to date 30 function StrToDate(const S: AnsiString; const useformat: ; separator: Char):TDateTime; Converts string to date 31 function StrToDate(const S: PChar; Len: Integer; const useformat: ; separator: Char = #0):TDateTime; Converts string to date 32 function StrToTime(const S: Shortstring):TDateTime; Converts string to time 33 function StrToTime(const S: Ansistring):TDateTime; Converts string to time 34 function StrToTime(const S: ShortString; separator: Char):TDateTime; Converts string to time 35 function StrToTime(const S: AnsiString; separator: Char):TDateTime; Converts string to time 36 function StrToTime(const S: ; FormatSettings: TFormatSettings):TDateTime; Converts string to time 37 function StrToTime(const S: PChar; Len: Integer; separator: Char = #0):TDateTime; Converts string to time 38 function SystemTimeToDateTime(const SystemTime: TSystemTime):TDateTime; Converts system time to datetime 39 function TimeStampToDateTime(const TimeStamp: TTimeStamp):TDateTime; Converts time stamp to DateTime 40 function TimeStampToMSecs(const TimeStamp: TTimeStamp):comp; Converts Timestamp to number of milliseconds 41 function TimeToStr(Time: TDateTime):; Returns string representation of Time 42 function TimeToStr(Time: TDateTime; const FormatSettings: TFormatSettings):; Returns string representation of Time 43 function Time: TDateTime; Get current time The following example illustrates the use of some of the above functions − Live Demo Program DatenTimeDemo; uses sysutils; var year, month, day, hr, min, sec, ms: Word; begin writeln (”Date and Time at the time of writing : ”,DateTimeToStr(Now)); writeln(”Today is ”,LongDayNames[DayOfWeek(Date)]); writeln; writeln(”Details of Date: ”); DecodeDate(Date,year,month,day); writeln (Format (”Day: %d”,[day])); writeln (Format (”Month: %d”,[month])); writeln (Format (”Year: %d”,[year])); writeln; writeln(”Details of Time: ”); DecodeTime(Time,hr, min, sec, ms); writeln (format(”Hour: %d:”,[hr])); writeln (format(”Minutes: %d:”,[min])); writeln (format(”Seconds: %d:”,[sec])); writeln (format(”Milliseconds: %d:”,[hr])); end. When the above code was compiled and executed, it produced the following result: Date and Time at the time of writing : 7/24/2012 8:26: Today is Tuesday Details of Date: Day:24 Month:7 Year: 2012 Details of Time: Hour: 8 Minutes: 26 Seconds: 21 Milliseconds: 8 Print Page Previous Next Advertisements ”;

Pascal – Decision Making

Pascal – Decision Making ”; Previous Next Decision making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. Following is the general form of a typical decision making structure found in most of the programming languages − Pascal programming language provides the following types of decision making statements. Click the following links to check their detail. Sr.No Statement & Description 1 if – then statement An if – then statement consists of a boolean expression followed by one or more statements. 2 If-then-else statement An if – then statement can be followed by an optional else statement, which executes when the boolean expression is false. 3 nested if statements You can use one if or else if statement inside another if or else if statement(s). 4 case statement A case statement allows a variable to be tested for equality against a list of values. 5 case – else statement It is similar to the if-then-else statement. Here, an else term follows the case statement. 6 nested case statements You can use one case statement inside another case statement(s). Print Page Previous Next Advertisements ”;

Pascal – Functions

Pascal – Functions ”; Previous Next Subprograms A subprogram is a program unit/module that performs a particular task. These subprograms are combined to form larger programs. This is basically called the ”Modular design.” A subprogram can be invoked by a subprogram/program, which is called the calling program. Pascal provides two kinds of subprograms − Functions − these subprograms return a single value. Procedures − these subprograms do not return a value directly. Functions A function is a group of statements that together perform a task. Every Pascal program has at least one function, which is the program itself, and all the most trivial programs can define additional functions. A function declaration tells the compiler about a function”s name, return type, and parameters. A function definition provides the actual body of the function. Pascal standard library provides numerous built-in functions that your program can call. For example, function AppendStr() appends two strings, function New() dynamically allocates memory to variables and many more functions. Defining a Function In Pascal, a function is defined using the function keyword. The general form of a function definition is as follows − function name(argument(s): type1; argument(s): type2; …): function_type; local declarations; begin … < statements > … name:= expression; end; A function definition in Pascal consists of a function header, local declarations and a function body. The function header consists of the keyword function and a name given to the function. Here are all the parts of a function − Arguments − The argument(s) establish the linkage between the calling program and the function identifiers and also called the formal parameters. A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of parameters of a function. Use of such formal parameters is optional. These parameters may have standard data type, user-defined data type or subrange data type. The formal parameters list appearing in the function statement could be simple or subscripted variables, arrays or structured variables, or subprograms. Return Type − All functions must return a value, so all functions must be assigned a type. The function-type is the data type of the value the function returns. It may be standard, user-defined scalar or subrange type but it cannot be structured type. Local declarations − Local declarations refer to the declarations for labels, constants, variables, functions and procedures, which are application to the body of function only. Function Body − The function body contains a collection of statements that define what the function does. It should always be enclosed between the reserved words begin and end. It is the part of a function where all computations are done. There must be an assignment statement of the type – name := expression; in the function body that assigns a value to the function name. This value is returned as and when the function is executed. The last statement in the body must be an end statement. Following is an example showing how to define a function in pascal − (* function returning the max between two numbers *) function max(num1, num2: integer): integer; var (* local variable declaration *) result: integer; begin if (num1 > num2) then result := num1 else result := num2; max := result; end; Function Declarations A function declaration tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately. A function declaration has the following parts − function name(argument(s): type1; argument(s): type2; …): function_type; For the above-defined function max(), following is the function declaration − function max(num1, num2: integer): integer; Function declaration is required when you define a function in one source file and you call that function in another file. In such case, you should declare the function at the top of the file calling the function. Calling a Function While creating a function, you give a definition of what the function has to do. To use a function, you will have to call that function to perform the defined task. When a program calls a function, program control is transferred to the called function. A called function performs defined task, and when its return statement is executed or when it last end statement is reached, it returns program control back to the main program. To call a function, you simply need to pass the required parameters along with function name, and if function returns a value, then you can store returned value. Following is a simple example to show the usage − Live Demo program exFunction; var a, b, ret : integer; (*function definition *) function max(num1, num2: integer): integer; var (* local variable declaration *) result: integer; begin if (num1 > num2) then result := num1 else result := num2; max := result; end; begin a := 100; b := 200; (* calling a function to get max value *) ret := max(a, b); writeln( ”Max value is : ”, ret ); end. When the above code is compiled and executed, it produces the following result − Max value is : 200 Print Page Previous Next Advertisements ”;

Pascal – Home

Pascal Tutorial PDF Version Quick Guide Resources Job Search Discussion Pascal is a procedural programming language, designed in 1968 and published in 1970 by Niklaus Wirth and named in honour of the French mathematician and philosopher Blaise Pascal. Pascal runs on a variety of platforms, such as Windows, Mac OS, and various versions of UNIX/Linux. This tutorial should introduce you to the understanding of Pascal to proceed with Delphi and other related frameworks etc. Audience This tutorial is designed for Software Professionals who are willing to learn Pascal Programming Language in simple and easy steps. This tutorial should give you basic understanding on Pascal Programming concepts, and after completing this tutorial, you should be at intermediate level of expertise from where you can take yourself to higher level of expertise. Prerequisites Before proceeding with this tutorial you should have a basic understanding of software basic concepts like what is source code, compiler, text editor and execution of programs, etc. If you already have understanding on any other computer programming language, then it will be an added advantage to proceed. Print Page Previous Next Advertisements ”;