Important Announcement
PubHTML5 Scheduled Server Maintenance on (GMT) Sunday, June 26th, 2:00 am - 8:00 am.
PubHTML5 site will be inoperative during the times indicated!

ppl

Published by rsagwal, 2022-04-27 08:37:29

Description: ppl

Search

Read the Text Version

if: An if statement provides for the conditional execution of either a statement or statement block based on whether a specified expression is true. Generally, it takes the form if (condition) statement; else statement; Some programming languages, such as Scheme and Perl, offer a negated version of the if statement: unless. case: Deeply nested if-else statements can often be correct syntactically and yet not express the intended logic of the programmer. Unintended else-if matchings, for example, are more likely to pass unnoticed. Modifications to the statements are also much harder to get right. That’s why, as an alternative method of choosing among a set of mutually exclusive choices, most programming languages provide a case statement. One point to keep in mind: many programming languages constrain the type of selector expression to integral values. That is, the following fragment may be rejected. switch (name) { case \"Deniz\": ... break; case \"Defne\": ... break; case \"Mete\": ... break; ... default: ... } /* end of switch(name) */ Example: A C++ program fragment that counts the number of occurrences of each vowel. //if-else version char ch; int aCnt = 0, eCnt = 0, iCnt = 0, oCnt = 0, uCnt = 0, consonantCnt = 0, othersCnt = 0; while (cin >> ch) if (ch == ‘a’ || ch == ‘A’) ++aCnt; else if (ch == ‘e’ || ch == ‘E’) ++eCnt; else if (ch == ‘i’ || ch == ‘I’) ++iCnt; else if (ch == ‘o’ || ch == ‘O’) ++oCnt; else if (ch == ‘u’ || ch == ‘U’) ++uCnt; else if (isalpha(ch)) ++consonantCnt; else ++othersCnt; Example: A C++ program fragment that counts the number of occurrences of each vowel. //switch-case version char ch; int aCnt = 0, eCnt = 0, iCnt = 0, oCnt = 0, uCnt = 0, consonantCnt = 0, othersCnt = 0; while (cin >> ch) PPL- 51 Dr. Rakesh Kumar June 20, 2021

switch (ch) { case 'a': case 'A': ++aCnt; break; case 'e': case 'E': ++eCnt; break; case 'i': case 'I': ++iCnt; break; case 'o': case 'O': ++oCnt; break; case 'u': case 'U': ++uCnt; break; default: if (isalpha(ch)) ++consonantCnt; else ++othersCnt; } /* end of switch(ch) */ Iteration Iterative composition is employed when part of a program is to be executed for zero or more times. There are four basic iteration constructs. Indexed Loop or deterministic loop We use this structure when we know the number of times the loop will be executed. An example is the for loop in Pascal. Example: A Pascal fragment that computes the summation of numbers from 1 to n. sum := 0; for counter := 1 to n do sum := sum + counter; Note that the for statement in C-based languages is a much more powerful, general construct and should be treated as a test-before (Pre-test) loop. In addition to implementing nondeterministic loops, deterministic ones can easily be simulated. For example, the above fragment can be written as for (sum = 0, counter = 1; counter <= n; counter++) sum += counter; Test-Before Loop or Pretest loop or Entry Controlled Loop Being one of the two nondeterministic loops, the condition is checked at the beginning of the loop. It means that the loop body may never get executed. A typical example is the while statement in ALGOL-based programming languages. Example: A C fragment to count the number of characters on a single line. for (n = 0; getchar() != ‘\\n’; ++n) /* no-op */ ; PPL- 52 Dr. Rakesh Kumar June 20, 2021

Note that the closing parenthesis is followed by an isolated semicolon. This means that the for loop contains a null statement. The general form of the for loop in C-based languages is given below: for (expression1; expression2; expression3) statement; expression-1 is evaluated once before the loop starts. It serves to make initializations. expression-2 is evaluated before each iteration and as soon as it evaluates to zero (or false in safer programming languages like Java and C#) execution will continue at the line following the for loop. expression-3 is evaluated at the end of each iteration. Any of these expressions can be omitted, although the semicolons must remain. If the first expression is omitted, the for loop simply does not perform any initializations. If the third expression is omitted, there won’t be any side effects taking place at the end of the iterations. As for the absence of the second expression, it will be taken to be true. That is, for ( ; ; ) statement; is same as while (any non-zero value) statement; In Java and C#, it is equivalent to while (true) statement; Test-After Loop or Post-test Loop or Exit Controlled Loop In the case of a test after loop, the condition is checked at the end of the loop. So, the loop body is executed at least once. Typical examples are the repeat-until statement in Pascal- based programming languages and do-while statement in C-based programming languages. Example: A C fragment that keeps reading from the input stream until 'a' is read. do {ch = getchar();} while (ch != ‘a’); Unconditional Loop In addition to these three constructs, some programming languages provide an unconditional looping structure. This structure is typically used together with an exit statement. An example to this is the LOOP-END structure in Modula-3. Example: A Modula-3 fragment that computes the summation of numbers from 1 to n. sum := 0; LOOP IF counter > n THEN EXIT; END; /* end of IF */ PPL- 53 Dr. Rakesh Kumar June 20, 2021

sum := sum + counter; INC(counter, 1); END; Goto Statement It has been shown that if constructs for selection and iteration are available, then any program can be written without the use of the goto statement. But it doesn’t mean that it is entirely useless. Different forms of iteration can also be written in terms of others. Does it mean that they are useless? No! Expressing the C-style for-loop in terms of the while-loop. for (expression1; expression2; expression3) statement; can be rewritten using while loop as follows expression1; while (expression2) { statement; expression3; } It is granted that goto is a rather low-level control structure and it had better be avoided where possible. But there may be places where it turns out to be the best choice. For instance, what can we do when we have to exit a loop prematurely? Some programming languages, such as C, C++, Java and Modula-3, as seen from the example of unconditional looping structure, provide control structures like break and continue; but there are programming languages that do not. The only answer in such cases is either to complicate the test expression of the loop or use a goto with its target as the statement following the end of the loop. So, the corollary is: avoid its use but don’t ever say that it is entirely useless. Control Over Subprograms Control at the subprogram level is concerned with subprogram invocation and the relationship between the calling module and the called module. What follows is a list of possible ways the caller and the callee are related. Simple Call In simple call, the caller exerts total control over the callee. That is, there is a master/slave relationship between them. PPL- 54 Dr. Rakesh Kumar June 20, 2021

When a subprogram is invoked, control of execution branches to the entry point of the subprogram, while the address of the next instruction, the one that will be processed after completion of the subprogram, is saved. When the exit point of the subprogram is encountered during execution, control returns to the caller and to the instruction corresponding to the address saved at the point of call. The constraints inherent in this sort of relationship between the caller and the callee are: A subprogram cannot call itself. The subprogram is invoked by means of an explicit call statement within the sequence of statements that make up the calling program. Only a single subprogram has control of execution at any one time. Thus, two subprograms cannot be invoked to execute concurrently. And the calling program has total control over the subordinate subprogram, as a master to slave. Recursion When we remove the first constraint in the above list we get recursion. A separate activation record (frame) is created for each invocation of the recursive subprogram. Considering the cost of a call instruction and space used in the run-time stack, it is fair to say that a recursive solution is likely to be less efficient than its iterative counterpart with regard to both time and space considerations. However, for the sake of fairness, it should be stressed that the cost is PPL- 55 Dr. Rakesh Kumar June 20, 2021

due to the call instruction, not recursion itself. Some programming languages require a subprogram to be explicitly declared recursive. Examples are PL/I and FORTRAN 90. Pre-90 versions of FORTRAN and COBOL do not even allow recursive subprogram definitions. The reason why such a crucial problem solving tool is ruled out is not because the designers of these programming language could not foresee the use of recursion. These programming languages, when they came out, had to compete with assembly and machine code. For making this goal more attainable, their designers decided to make all data entities static, which automatically excluded the possibility of recursion (Because recursion requires dynamic memory management). Implicit Calls When we lift the requirement that subprograms must be called explicitly, we have the possibility of subprograms being called outside the control of the programmer. This happens in two ways: (a) Exception Handling: An exception is an event that occurs unexpectedly, infrequently, and at random intervals. Examples are divide by zero, subscript out of range, and end-of-file. An exception handler is a subprogram written by the programmer, interfaces with the operating system, and is invoked only when a specified “exceptional condition” is encountered. (b) Scheduled Call: A scheduled call is typical of the type of subprogram control used in event-oriented simulation programs. Control over some subprograms is managed by a timing mechanism, a subprogram that may be built into the programming language or coded by the programmer. For example, suppose subprogram A \"calls\"—that is, pre-schedules— subprogram B with a particular activation time. An activation record is created for subprogram B and inserted into a queue maintained in ascending order by activation time. The timing routine periodically examines the first record in this queue; when its activation time matches the current simulated time, the record is removed from the queue, placed on the run-time stack, and the subprogram is invoked. Subprograms may also be scheduled to occur not at an explicit time, but \"as soon as possible.\" This might occur when the subprogram depends on the availability of a particular resource or the completion of another subprogram. Parallel Processing Parallel processing, also called concurrent processing, refers to the concurrent execution of two or more subprograms in order to solve a specific problem. Parallelism may be real, that PPL- 56 Dr. Rakesh Kumar June 20, 2021

is, executing simultaneously in real time on multiple processors, or virtual, simulated parallelism on a single central processor. Example: Tasks in Ada83. Suppose that the accounting office of a small firm is responsible for carrying out these functions (tasks): ordering supplies, paying bills, and preparing invoices. With one accountant, the process might be represented as: PROCEDURE Accounting IS BEGIN Order_Supplies; Pay_Bills; Prepare_Invoices; END Accounting; With three accountants, however, the tasks could be performed in parallel. A typical Ada representation of such a situation would be: PROCEDURE Accounting IS TASK Order; TASK BODY Order IS BEGIN Order_Supplies; END Order; TASK Pay; TASK BODY Pay IS BEGIN Pay_Bills; END Pay; BEGIN Prepare_Invoices; END Accounting; In designing programs with parallel control, a programmer must consider some important problems including synchronization, critical section, and deadlock. Coroutines If we remove the requirement of caller having total control over callee, we get mutual control. Subprograms exerting mutual control over each other are called coroutines. Coroutines can each call the other. But, different from an ordinary call, a call by B to A actually transfers control to the point in subprogram A where A last called B. A different keyword, such as resume, may be used in place of call. PPL- 57 Dr. Rakesh Kumar June 20, 2021

The way different processes in an operating system are related to each other is pretty much the same. When a process gives up the processor another process gets executed on the processor. Once that process completes its time slot, it yields the processor, probably back to the previous process. This process does not start execution from the first line but rather from where it left off before. =============================================== Compilation A compiler is a program that reads a program written in one language - the source language - and translate it into an equivalent program in another language - the target language. The Analysis-Synthesis Model of Compilation There are two parts to compilation: analysis and synthesis. The analysis part breaks up the source program into constituent pieces and creates an intermediate representation of the source program. The synthesis part constructs the desired target program from the intermediate representation. Of the two parts, synthesis requires the most specialized technique. ANALYSIS OF THE SOURCE PROGRAM In compiling, analysis consists of three phases: 1. Linear analysis, in which the stream of characters making up the source program is read PPL- 58 Dr. Rakesh Kumar June 20, 2021

from left-to-right and grouped into tokens that are sequences of characters having a collective meaning. 2. Hierarchial analysis, in which characters or tokens are grouped hierarchically into nested collections with collective meaning. 3. Semantic analysis, in which certain checks are performed to ensure that the components of a program fit together meaningfully. Lexical Analysis In a compiler, linear analysis is called lexical analysis or scanning. For example, in lexical analysis, the characters in the following assignment statement position := initial + rate * 60 would be grouped into the following tokens: 1. The identifier position. PPL- 59 Dr. Rakesh Kumar June 20, 2021

2. The assignment symbol :=. 3. The identifier initial. 4. The plus sign. 5. The identifier rate. 6. The multiplication sign. 7. The number 60. The blanks separating the characters of these tokens would normally be eliminated during lexical analysis. Tokens or Lexical Units Lexemes are said to be a sequence of characters (alphanumeric) in a token. There are some predefined rules for every lexeme to be identified as a valid token. These rules are defined by grammar rules, by means of a pattern. A pattern explains what can be a token, and these patterns are defined by means of regular expressions. In programming language, keywords, constants, identifiers, strings, numbers, operators and punctuations symbols can be considered as tokens. Longest Match Rule When the lexical analyzer read the source-code, it scans the code letter by letter; and when it encounters a whitespace, operator symbol, or special symbols, it decides that a word is completed. For example: int intvalue; While scanning both lexemes till ‘int’, the lexical analyzer cannot determine whether it is a keyword int or the initials of identifier int value. The Longest Match Rule states that the lexeme scanned should be determined based on the longest match among all the tokens available. The lexical analyzer also follows rule priority where a reserved word, e.g., a keyword, of a language is given priority over user input. That is, if the lexical analyzer finds a lexeme that matches with any existing reserved word, it should generate an error. Syntax Analysis PPL- 60 Dr. Rakesh Kumar June 20, 2021

Hierarchical analysis is called parsing or syntax analysis. It involves grouping the tokens of the source program into grammatical phrases that are used by the compiler to synthesize output. Usually, the grammatical phrases of the source program are represented by a parse tree. A parse tree or parsing tree is an ordered, rooted tree that represents the syntactic structure of a string according to some context-free grammar. The hierarchical structure of a program is usually expressed by recursive rules. For example, we might have the following rules as part of the definition of expressions: 1. Any identifier is an expression. 2. Any number is an expression. 3. If expression1 and expression2 are expressions, then so are expression1 + expression2 expression1 * expression2 ( expression1 ) Rules (1) and (2) are (non-recursive) basis rules, while (3) defines expressions in terms of operators applied to other expressions. A lexical analyzer can identify tokens with the help of regular expressions and pattern rules. But a lexical analyzer cannot check the syntax of a given sentence due to the limitations of the regular expressions. Regular expressions cannot check balancing tokens, such as parenthesis. Therefore, this phase uses context-free grammar (CFG), which is recognized by push-down automata. Semantic Analysis The semantic analysis phase checks the source program for semantic errors and gathers PPL- 61 Dr. Rakesh Kumar June 20, 2021

type information for the subsequent code-generation phase. It uses the hierarchical structure determined by the syntax-analysis phase to identify the operators and operands of expressions and statements. An important component of semantic analysis is type checking. Here the compiler checks that each operator has operands that are permitted by the source language specification. For example, many programming language definitions require a compiler to report an error every time a real number is used to index an array. However, the language specification may permit some operand coercions, for example, when a binary arithmetic operator is applied to an integer and real. In this case, the compiler may need to convert the integer to a real. Synthesis Phase of Compilation After semantic analysis the compiler generates an intermediate code of the source code for the target machine. It represents a program for some abstract machine. It is in between the high-level language and the machine language. This intermediate code should be generated in such a way that it makes it easier to be translated into the target machine code. Code Optimization The next phase does code optimization of the intermediate code. Optimization can be assumed as something that removes unnecessary code lines, and arranges the sequence of statements in order to speed up the program execution without wasting resources (CPU, memory). Some examples of code optimization are frequency reduction, strength reduction. Frequency Reduction Frequency reduction is a type in loop optimization process which is machine independent. In frequency reduction code inside a loop is optimized to improve the running time of program. Frequency reduction is used to decrease the amount of code in a loop. A statement or expression, which can be moved outside the loop body without affecting the semantics of the program, is moved outside the loop. Objective of Frequency Reduction The objective of frequency reduction is:  To reduce the evaluation frequency of expression.  To bring loop invariant statements out of the loop. Below is the example of Frequency Reduction: Program 1: PPL- 62 Dr. Rakesh Kumar June 20, 2021

// This program does not uses frequency reduction. int main() { int a = 2, b = 3, c, i = 0; while (i < 5) { c = pow(a, b) + pow(b, a); // c is calculated 5 times cout << c << endl;// print the value of c 5 times i++; } } Program 2: //This program uses frequency reduction. int main() { int a = 2, b = 3, c, i = 0; c = pow(a, b) + pow(b, a);// c is calculated outside the loop while (i < 5) { cout << c << endl;// print the value of c 5 times i++; } } Output: 17 17 17 17 17 Explanation Program 2 is more efficient than Program 1 as in Program 1 the value of c is calculated each time the while loop is executed. Hence the value of c is calculated outside the loop only once and it reduces the amount of code in the loop. PPL- 63 Dr. Rakesh Kumar June 20, 2021

Strength reduction: There are expressions that consume more CPU cycles, time, and memory. These expressions should be replaced with cheaper expressions without compromising the output of expression. For example, multiplication (x * 2) is expensive in terms of CPU cycles than (x << 1) and yields the same result. Code Generation In this phase, the code generator takes the optimized representation of the intermediate code and maps it to the target machine language. The code generator translates the intermediate code into a sequence of (generally) re-locatable machine code. Sequence of instructions of machine code performs the task as the intermediate code would do. Recursive Descent Parsing There are generally two types of Parsers: (1) Top-Down Parsers In this Parsing technique we expand the start symbol to the whole program. Examples: Recursive Descent and LL parsers are the Top-Down parsers. (2) Bottom-Up Parsers In this Parsing technique we reduce the whole program to start symbol. Examples: Operator Precedence Parser, LR(0) Parser, SLR Parser, LALR Parser and CLR Parser are the Bottom- Up parsers. Recursive Descent Parser It is a kind of Top-Down Parser. A top-down parser builds the parse tree from the top to down, starting with the start non-terminal. a recursive descent parser built from a set of mutually recursive procedures (or a non-recursive equivalent) where each such procedure implements one of the nonterminals of the grammar. This parsing technique recursively parses the input to make a parse tree, which may or may not require back-tracking. But the grammar associated with it (if not left factored) cannot avoid back-tracking. A form of recursive-descent parsing that does not require any back-tracking is known as predictive parsing. In order to use recursive descent parser, we have to eliminate left recursion and left factoring from the grammar. PPL- 64 Dr. Rakesh Kumar June 20, 2021

This parsing technique is regarded recursive as it uses context-free grammar which is recursive in nature. Back-tracking Top- down parsers start from the root node (start symbol) and match the input string against the production rules to replace them (if matched). To understand this, take the following example of CFG: S → rXd | rZd X → oa | ea Z → ai For an input string: read, a top-down parser, will behave like this: It will start with S from the production rules and will match its yield to the left-most letter of the input, i.e. ‘r’. The very production of S (S → rXd) matches with it. So the top-down parser advances to the next input letter (i.e. ‘e’). The parser tries to expand non-terminal ‘X’ and checks its production from the left (X → oa). It does not match with the next input symbol. So the top-down parser backtracks to obtain the next production rule of X, (X → ea). Now the parser matches all the input letters in an ordered manner. The string is accepted. Object Oriented Concepts Abstract Data Types Abstract Data type (ADT) is a type (or class) for objects whose behaviour is defined by a set of value and a set of operations. The definition of ADT only mentions what operations are to be performed but not how these operations will be implemented. It does not specify how data will be organized in memory and what algorithms will be used for implementing the operations. It is called “abstract” because it gives an implementation-independent view. The process of providing only the essentials and hiding the details is known as abstraction. PPL- 65 Dr. Rakesh Kumar June 20, 2021

The user of data type does not need to know how that data type is implemented, for example, we have been using Primitive values like int, float, char data types only with the knowledge that these data type can operate and be performed on without any idea of how they are implemented. So a user only needs to know what a data type can do, but not how it will be implemented. Think of ADT as a black box which hides the inner structure and design of the data type. For example in a stack abstract data type a Stack contains elements of the same type arranged in sequential order. All operations take place at a single end that is top of the stack and following operations can be performed: • push() – Insert an element at one end of the stack called top. • pop() – Remove and return the element at the top of the stack, if it is not empty. • peek() – Return the element at the top of the stack without removing it, if the stack is not empty. • size() – Return the number of elements in the stack. • isEmpty() – Return true if the stack is empty, otherwise return false. • isFull() – Return true if the stack is full, otherwise return false. There are two parts to each ADT: (1) The public or external part, which consists of: • the conceptual picture (the user's view of what the object looks like, how the PPL- 66 Dr. Rakesh Kumar June 20, 2021

structure is organized) • the conceptual operations (what the user can do to the ADT) (2) The private or internal part, which consists of: • the representation (how the structure is actually stored) • the implementation of the operations (the actual code) In general, there are many possible operations that could be defined for each ADT; however, they often fall into these categories: (1) initialize (2) add data (3) access data (4) remove data Benefits of using Abstract Data Types (a) Code is easier to understand (e.g., it is easier to see \"high-level\" steps being performed, not obscured by low-level code). (b) Implementations of ADTs can be changed (e.g., for efficiency) without requiring changes to the program that uses the ADTs. (c) ADTs can be reused in future programs. Information Hiding Information hiding is the process of hiding the details of an object or function. The hiding of these details results in an abstraction, which reduces the external complexity and makes the object or function easier to use. In addition, information hiding effectively decouples the calling code from the internal workings of the object or function being called, which makes it possible to change the hidden portions without having to also change the calling code. Encapsulation is a common technique programmers use to implement information hiding. PPL- 67 Dr. Rakesh Kumar June 20, 2021

The general idea of this mechanism is simple. If you have an attribute that is not visible from the outside of an object, and bundle it with methods that provide read or write access to it, then you can hide specific information and control access to the internal state of the object. In object-oriented programming language, these methods as getter and setter methods. As the names indicate, a getter method retrieves an attribute, and a setter method changes it. Depending on the methods that you implement, you can decide if an attribute can be read and changed, or if it’s read-only, or if it is not visible at all. You can also use the setter method to implement additional validation rules to ensure that your object always has a valid state. Encapsulation Encapsulation is a powerful feature that leads to information hiding and abstract data type. They encapsulate all the essential properties of the object that are to be created. Using the method of encapsulation the programmer cannot access the class directly. Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that binds together code and the data it manipulates. Other way to think about encapsulation is, it is a protective shield that prevents the data from being accessed by the code outside this shield. • Technically in encapsulation, the variables or data of a class is hidden from any other class and can be accessed only through any member function of own class in which they are declared. • As in encapsulation, the data in a class is hidden from other classes using the data hiding concept which is achieved by making the members or methods of class as private and the class is exposed to the end user or the world without providing any details behind implementation using the abstraction concept, so it is also known as combination of data-hiding and abstraction. • Encapsulation can be achieved by declaring all the variables in the class as private and writing public methods in the class to set and get the values of variables. Abstract Class PPL- 68 Dr. Rakesh Kumar June 20, 2021

An abstract class is a template definition of methods and variables of a class (category of objects) that contains one or more abstracted methods. Abstract classes are used in all object-oriented programming (OOP) languages, including Java, C++, C# and VB.NET. Objects or classes may be abstracted, which means that they are summarized into characteristics that are relevant to the current program’s operation. Individual instances resulting from classes are objects. Declaring a class as abstract means that it cannot be directly instantiated, which means that an object cannot be created from it. That protects the code from being used incorrectly. Abstract classes require subclasses to further define attributes necessary for individual instantiation. Abstract classes contrast with concrete classes, which are the default type. A concrete class has no abstracted methods and can be instantiated and used in code. In JAVA, the abstract keyword is a non-access modifier, used for classes and methods: • Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class). • Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided by the subclass (inherited from). An abstract class can have both abstract and regular methods. Inheritance Inheritance is a mechanism in which one class acquires the property of another class. With inheritance, we can reuse the fields and methods of the existing class. Hence, inheritance facilitates Reusability and is an important concept of OOPs. Sub Class: The class that inherits properties from another class is called Sub class or Derived Class. Super Class:The class whose properties are inherited by sub class is called Base Class or Super class. Types of inheritance There are various types of inheritance, based on paradigm and specific language. Single inheritance where subclasses inherit the features of one superclass. A class acquires the properties of another class. PPL- 69 Dr. Rakesh Kumar June 20, 2021

Multiple inheritance where one class can have more than one superclass and inherit features from all parent classes. Multilevel inheritance Where a subclass is inherited from another subclass. The class A serves as a base class for the derived class B, which in turn serves as a base class for the derived class C. The class B is known as intermediate base class because it provides a link for the inheritance between A and C. The chain ABC is known as inheritance path. A derived class with multilevel inheritance is declared as follows: Class A(...); // Base class Class B : public A(...); // B derived from A Class C : public B(...); // C derived from B This process can be extended to any number of levels. Hierarchical inheritance This is where one class serves as a superclass (base class) for more than one sub class. For example, a parent class, A, can have two subclasses B and C. Both B and C's parent class is A, but B and C are two separate subclasses. PPL- 70 Dr. Rakesh Kumar June 20, 2021

Hybrid inheritance Hybrid inheritance is when a mix of two or more of the above types of inheritance occurs. An example of this is when class A has a subclass B which has two subclasses, C and D. This is a mixture of both multilevel inheritance and hierarchal inheritance. Polymorphism It is the ability to appear in many forms. In object-oriented programming, polymorphism refers to a programming language's ability to process objects differently depending on their data type or class. It is the provision of a single interface to entities of different types or the use of a single symbol to represent multiple different types. More specifically, it is the ability to redefine methods for derived classes. For example, given a base class shape, polymorphism enables the programmer to define different area methods for any number of derived classes, such as circles, rectangles and triangles. No matter what shape an object is, applying the area method to it will return the correct results. Polymorphism is considered to be a requirement of any true object-oriented programming language (OOPL). program Adhoc; function Add(x, y : Integer) : Integer; begin Add := x + y end; function Add(s, t : String) : String; begin Add := Concat(s, t) end; begin Writeln(Add(1, 2)); (* Prints \"3\" *) Writeln(Add('Hello, ', 'Mammals!')); (* Prints \"Hello, Mammals!\" *) end. PPL- 71 Dr. Rakesh Kumar June 20, 2021

Static and dynamic polymorphism Polymorphism can be distinguished by when the implementation is selected: statically (at compile time) or dynamically (at run time, typically via a virtual function). This is known respectively as static dispatch and dynamic dispatch, and the corresponding forms of polymorphism are accordingly called static polymorphism and dynamic polymorphism. Static polymorphism executes faster, because there is no dynamic dispatch overhead, but requires additional compiler support. Further, static polymorphism allows greater static analysis by compilers (notably for optimization), source code analysis tools, and human readers (programmers). Dynamic polymorphism is more flexible but slower. ============================================================= Scripting Languages All scripting languages are programming languages. The scripting language is basically a language where instructions are written for a run time environment. They do not require the compilation step and are rather interpreted. It brings new functions to applications and glue complex system together. A scripting language is a programming language designed for integrating and communicating with other programming languages. There are many scripting languages some of them are discussed below: (a) bash: It is a scripting language to work in the Linux interface. It is a lot easier to use bash to create scripts than other programming languages. It describes the tools to use and code in the command line and create useful reusable scripts and conserve documentation for other people to work with. (b) Node js: It is a framework to write network applications using JavaScript. Corporate users of Node.js include IBM, LinkedIn, Microsoft, Netflix, PayPal, Yahoo for real-time web applications. (c) Ruby: There are a lot of reasons to learn Ruby programming language. Ruby’s flexibility has allowed developers to create innovative software. It is a scripting language which is great for web development. (d) Python: It is easy, free and open source. It supports procedure-oriented programming and object-oriented programming. Python is an interpreted language with dynamic semantics and huge lines of code are scripted and is currently the most hyped language among developers. (e) Perl: A scripting language with innovative features to make it different and popular. Found PPL- 72 Dr. Rakesh Kumar June 20, 2021

on all windows and Linux servers. It helps in text manipulation tasks. High traffic websites that use Perl extensively include priceline.com, IMDB. Advantages of scripting languages (a) Easy learning: The user can learn to code in scripting languages quickly, not much knowledge of web technology is required. (b) Fast editing: It is highly efficient with the limited number of data structures and variables to use. (c) Interactivity: It helps in adding visualization interfaces and combinations in web pages. Modern web pages demand the use of scripting languages. To create enhanced web pages, fascinated visual description which includes background and foreground colors and so on. (d) Functionality: There are different libraries which are part of different scripting languages. They help in creating new applications in web browsers and are different from normal programming languages. Application of Scripting Languages Scripting languages are used in many areas: (a) Scripting languages are used in web applications. It is used in server side as well as client side. Server side scripting languages are: JavaScript, PHP, Perl etc. and client side scripting languages are: JavaScript, AJAX, jQuery etc. (b) Scripting languages are used in system administration. For example: Shell, Perl, Python scripts etc. (c) It is used in Games application and Multimedia. (d) It is used to create plugins and extensions for existing applications. History Scripting languages are not new: they have existed since at least the 1960s. However, the power and sophistication of scripting languages have improved dramatically in recent years. When coupled with tremendous increases in computer speed, it has become possible to use scripting languages for a much broader range of applications than was possible previously. Nearly every major computing platform over the last four decades has supported both system programming languages (for creating applications from scratch) and scripting languages (for integrating components and applications). Here are a few examples of significant scripting languages, in rough chronological order. PPL- 73 Dr. Rakesh Kumar June 20, 2021

JCL (Job Control Language) Used to sequence job steps and arrange the flow of data in card decks for OS/360, starting in the 1960s. JCL may have been the first widely used scripting language, though it is a relatively primitive one by today's standards. Unix shells (sh, csh, ksh, ...) The first shell, sh, was written for the Unix operating system in the early 1970's and a series of others followed over the next 20 years. Shell programs are used both for typing interactive commands and for writing scripts that automate common tasks. One of the most unique and powerful aspects of Unix was the ability to write shell scripts that create new applications by composing existing applications; it is perhaps the single most important reason for Unix's popularity as a platform for application developers. Rexx Michael Cowlishaw initially conceived the Rexx language in 1979 to simplify programming tasks on IBM's CMS timesharing system. It became popular as a macro language for arbitrary application programs, and its usage spread to many other platforms, including PCs and Unix. Perl Created by Larry Wall in the late 1980s as a way to bring together in one place the functions of many popular Unix text processing applications such as sh, sed, and awk, Perl quickly became a favorite tool of system administrators. With the arrival of the World-Wide Web, Perl achieved even greater fame as a convenient way to write CGI scripts for dynamic Web pages. Tcl Created by John Ousterhout in the late 1980s as an embeddable command language for interactive tools. When supplemented with the Tk toolkit, it became popular as the fastest way to build graphical user interfaces on Unix. Tcl and Tk were ported to Windows and the Macintosh in the mid 1990s, producing an outstanding cross-platform development environment. Today Tcl is used for a wide variety of integration applications including Web content generation, financial applications, electronic design automation, automated testing, and system management. Visual Basic This Microsoft product lies somewhere between a scripting language and a system programming language. It became popular in the early 1990s as the easiest way to create PPL- 74 Dr. Rakesh Kumar June 20, 2021

graphical user interfaces under Windows. The combination of Visual Basic and VBX (later ActiveX) components is probably the most successful component framework in existence, due in large part to the ease of integration provided by Visual Basic. Python Python is a dynamic object-oriented language, created by Guido van Rossum in the early 1990s to bridge the gap between shell and C programming. Its elegant, easy to learn syntax, high level data types, elaborate library, portability, and ease of extending and embedding in C/ C++ all contribute to its popularity. Originally designed as an advanced scripting language, it found new uses as a rapid application development language for web, database and GUI applications, as well as for distributed systems and mobile code. JavaScript Created in the mid 1990s by Netscape Corporation to perform scripting functions in Web browsers, such as simple form validation. JavaScript has become the de facto standard for client-side Web scripting, although it doesn't have much to do with Java. PPL- 75 Dr. Rakesh Kumar June 20, 2021


Like this book? You can publish your book online for free in a few minutes!
Create your own flipbook