Objective-C Categories ”; Previous Next Sometimes, you may find that you wish to extend an existing class by adding behavior that is useful only in certain situations. In order add such extension to existing classes, Objective-C provides categories and extensions. If you need to add a method to an existing class, perhaps, to add functionality to make it easier to do something in your own application, the easiest way is to use a category. The syntax to declare a category uses the @interface keyword, just like a standard Objective-C class description, but does not indicate any inheritance from a subclass. Instead, it specifies the name of the category in parentheses, like this − @interface ClassName (CategoryName) @end Characteristics of Category A category can be declared for any class, even if you don”t have the original implementation source code. Any methods that you declare in a category will be available to all instances of the original class, as well as any subclasses of the original class. At runtime, there”s no difference between a method added by a category and one that is implemented by the original class. Now, let”s look at a sample category implementation. Let”s add a category to the Cocoa class NSString. This category will make it possible for us to add a new method getCopyRightString which helps us in returning the copyright string. It is shown below. Live Demo #import <Foundation/Foundation.h> @interface NSString(MyAdditions) +(NSString *)getCopyRightString; @end @implementation NSString(MyAdditions) +(NSString *)getCopyRightString { return @”Copyright TutorialsPoint.com 2013″; } @end int main(int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; NSString *copyrightString = [NSString getCopyRightString]; NSLog(@”Accessing Category: %@”,copyrightString); [pool drain]; return 0; } Now when we compile and run the program, we will get the following result. 2013-09-22 21:19:12.125 Categories[340:303] Accessing Category: Copyright TutorialsPoint.com 2013 Even though any methods added by a category are available to all instances of the class and its subclasses, you”ll need to import the category header file in any source code file where you wish to use the additional methods, otherwise you”ll run into compiler warnings and errors. In our example, since we just have a single class, we have not included any header files, in such a case we should include the header files as said above. Print Page Previous Next Advertisements ”;
Category: Computer Programming
Objective-C – Useful Resources ”; Previous Next The following resources contain additional information on Objective C. Please use them to get more in-depth knowledge on this topic. Useful Video Courses Understanding S.M.A.R.T. Objectives 19 Lectures 1 hours PARTHA MAJUMDAR More Detail Econometrics For Dummies: Learn The Basic 20 Lectures 51 mins Pedro Planas More Detail Master Creating Well-Defined Marketing Objectives in 30 mins 6 Lectures 25 mins Ken Burke More Detail Build Landing Page Design for Higher Sales & Lead Generation 20 Lectures 1.5 hours Being Commerce More Detail Build Landing Page Optimization for higher conversion rate 20 Lectures 1.5 hours Being Commerce More Detail RECRUITMENT: IT basics for IT Recruiters Featured 61 Lectures 5 hours Valeria Frisch More Detail 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 ”;
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 ”;