PPL 2
PPL 2
Preliminary Concepts:
Reasons for studying concepts of programming languages,
programming domains,
language evaluation criteria,
influences on language design,
language categories,
language design trade-offs,
implementation methods,
programming environments,
Evolution of Major Programming Languages.
Syntax and Semantics:
General problem of describing syntax,
formal methods of describing syntax,
attribute grammars,
describing the meanings of programs
Preliminary Concepts
• Language in which they develop S/W places limits on the kinds of control
structures, data structures, and abstractions they can use.
https://jntuhbtechadda.blogspot.com/
• If these programmers were familiar with other languages available, they
would be in a better position to make informed language choices.
• Many believe that ALGOL 60 was a better language than Fortran; however,
Fortran was most widely used. It is attributed to the fact that the
programmers and managers didn‘t understand the conceptual design of
ALGOL 60.
Programming Domains
Scientific applications
• In the early 40s computers were invented for scientific applications.
• The applications require large number of floating-point computations.
• Fortran was the first language developed scientific applications.
• ALGOL 60 was intended for the same use.
https://jntuhbtechadda.blogspot.com/
Business applications
• The first successful language for business was COBOL.
• Produce reports, use decimal arithmetic numbers and characters.
• The arrival of PCs started new ways for businesses to use computers.
• Spreadsheets and database systems were developed for business.
Artificial intelligence
• Symbolic rather than numeric computations are manipulated.
• Symbolic computation is more suitably done with linked lists than arrays.
• LISP was the first widely used AI programming language.
Systems programming
• The O/S and all of the programming supports tools are collectively known
as its system software.
• Need efficiency because of continuous use
Scripting languages
• Put a list of commands, called a script, in a file to be executed.
• PHP is a scripting language used on Web server systems. Its code is
embedded in HTML documents. The code is interpreted on the server
before the document is sent to a requesting browser.
Readability
• Software development was largely thought of in term of writing code
o LOC.
• Language constructs were designed more from the point of view computer
than the users.
https://jntuhbtechadda.blogspot.com/
• Multiplicity of features is also a complicating characteristic
o having more than one way to accomplish a particular operation.
• Ex ―Java:
count = count + 1
count += 1 count ++
++count
• Although the last two statements have slightly different meaning from
each other and from the others, all four have the same meaning when used
as stand-alone expressions.
• Operator overloading where a single operator symbol has more than one
meaning.
Orthogonality:
• Makes the language easy to learn and read.
• The more orthogonal the design of a language, the fewer exceptions the
language rules require.
Control Statements
• It became widely recognized that indiscriminate use of goto statements
severely reduced program readability.
https://jntuhbtechadda.blogspot.com/
{
while (sum <= 100)
{
sum += incr;
}
incr++;
}
if C didn‘t have a loop construct, this would be written as follows:
loop1:
if (incr >= 20) go to out;
loop2:
if (sum > 100) go to next;
sum += incr;
go to loop2;
next:
incr++;
go to loop1: out:
• Basic and Fortran in the early 70s lacked the control statements that allow
strong restrictions on the use of gotos, so writing highly readable programs
in those languages was difficult.
Syntax Considerations
• The syntax of the elements of a language has a significant effect on
readability.
https://jntuhbtechadda.blogspot.com/
readability. ANSI BASIC (1978) an identifier could consist only of a single letter
of a single letter followed by a single digit.
Writability
• It is a measure of how easily a language can be used to create programs
for a chosen problem domain.
• Most of the language characteristics that affect readability also affect
writability.
Expressivity
• It means that a language has relatively convenient, rather than
cumbersome, ways of specifying computations.
• Ex:
++count ⇔ count = count + 1 // more convenient and shorter
Reliability
A program is said to be reliable if it performs to its specifications under all
conditions.
Type checking: is simply testing for type errors in a given program, either
by the compiler or during program execution.
https://jntuhbtechadda.blogspot.com/
• The earlier errors are detected, the less expensive it is to make the required
repairs. Java requires type checking of nearly all variables and
expressions at compile time.
Cost
Categories
o Training programmers to use language
o Writing programs ―Writability‖
o Compiling programs
o Executing programs
o Language implementation system ―Free compilers is the key,
success of Java
o Reliability, does the software fail?
o Maintaining programs: Maintenance costs can be as high as two to
four times as much as development costs.
o Portability ―standardization of the language, Generality (the
applicability to a wide range of applications)
Programming methodologies
https://jntuhbtechadda.blogspot.com/
• 1950s and early 1960s: Simple applications; worry about machine
efficiency
Language categories
Imperative
• Central features are variables, assignment statements, and iteration
• C, Pascal
Functional
• Main means of making computations is by applying functions to given
parameters
• LISP, Scheme
Logic
• Rule-based
• Rules are specified in no special order
• Prolog
Object-oriented
• Encapsulate data objects with processing
• Inheritance and dynamic type binding
• Grew out of imperative languages – C++, Java
https://jntuhbtechadda.blogspot.com/
Implementation methods
• The major methods of implementing programming languages are
compilation, pure interpretation, and hybrid implementation
Compilation
• Translate high-level program (source language) into machine code
(machine language)
https://jntuhbtechadda.blogspot.com/
• Compilation process has several phases:
https://jntuhbtechadda.blogspot.com/
• Fetch-execute-cycle (on a von Neumann architecture)
initialize the program counter
repeat forever
fetch the instruction pointed by the counter
increment the counter
decode the instruction
execute the instruction
end repeat
Pure Interpretation
https://jntuhbtechadda.blogspot.com/
• Bottleneck: Statement decoding, rather than the connection between the
processor and memory, is the bottleneck of a pure interpreter.
https://jntuhbtechadda.blogspot.com/
• Examples:
o Perl programs are partially compiled to detect errors before
interpretation
Programming environments
• The collection of tools used in software development
• UNIX
o An older operating system and tool collection
• Borland JBuilder
o An integrated development environment for Java
• Microsoft Visual Studio.NET
o A large, complex visual environment
o Used to program in C#, Visual BASIC.NET, Jscript, J#, or C++
• This followed the punch cards encoded data in 20th century that used to
direct the mechanical processing. In the 1930s and early 1940s lambda
calculus remained the influential in language design.
• The decade of 1940s has many landmarks to its credit in the initial
development of modern computers and programming languages.
https://jntuhbtechadda.blogspot.com/
• The 1GL programming was quickly superseded by similarly machine-
specific, but mnemonic, second generation languages (2GL) known as
assembly languages or “assembler”.
https://jntuhbtechadda.blogspot.com/
• Other languages have been developed to permit programming in Internet
applications. The most popular is Java, an Object-Oriented programming
language introduced in 1995 by Sun Microsystems. Java enables the
distribution of both the data and small applications called applets.
• The semantics of this statement form is that when the current value
of the Boolean expression is true, the embedded statement is
executed.
Lexemes Tokens
index identifier
= equal_sign
2 int_literal
* mult_op
count identifier
+ plus_op
17 int_literal
; semicolon
https://jntuhbtechadda.blogspot.com/
Language Recognizers and Generators
• In general, language can be formally defined in two distinct ways: by
recognition and by generation.
• Language Recognizers:
o A recognition device reads input strings of the language and decides
whether the input strings belong to the language.
o It only determines whether given programs are in the language.
o Example: syntax analyzer part of a compiler. The syntax analyzer,
also known as parsers, determines whether the given programs are
syntactically correct.
• Language Generators:
o A device that generates sentences of a language
o One can determine if the syntax of a particular sentence is correct
by comparing it to the structure of the generator
Context-free Grammars
o Developed by Noam Chomsky in the mid-1950s who described four
classes of generative devices or grammars that define four classes
of languages.
https://jntuhbtechadda.blogspot.com/
Fundamentals
o A metalanguage is a language used to describe another language
“Ex: BNF.”
o The lexemes and tokens of the rules are called terminal symbols or
terminals.
Describing Lists
o Syntactic lists are described using recursion.
<ident_list> → ident
| ident, <ident_list>
https://jntuhbtechadda.blogspot.com/
o A derivation is a repeated application of rules, starting with the start
symbol and ending with a sentence (all terminal symbols)
o An example grammar:
<program> → <stmts>
<stmts> → <stmt> | <stmt> ; <stmts>
<stmt> → <var> = <expr>
<var> → a | b | c | d
<expr> → <term> + <term> | <term> - <term>
<term> → <var> | const
Parse Trees
o Hierarchical structures of the language are called parse trees.
o A parse tree for the simple statement A = B + const
<program>
|
<smts>
|
<smt>
/|\
<var> = <exp>
| /|\
a <term> + <term>
| |
<var> const
|
b
https://jntuhbtechadda.blogspot.com/
Ambiguity
o A grammar is ambiguous if it generates a sentential form that has
two or more distinct parse trees.
o Ex: Two distinct parse trees for the same sentence, const – const /
const
<expr> → <expr> <op> <expr> | const
<op> → / | -
Operator Precedence
• The fact that an operator in an arithmetic expression is generated lower
in the parse tree can be used to indicate that it has higher precedence over
an operator produced higher up in the tree.
https://jntuhbtechadda.blogspot.com/
• In the left parsed tree above, one can conclude that the * operator has
precedence over the + operator. How about the tree on the right-hand side?
https://jntuhbtechadda.blogspot.com/
• Rightmost derivation of the sentence A = B + C * A
Associativity of Operators
• Do parse trees for expressions with two or more adjacent occurrences of
operators with equal precedence have those occurrences in proper
hierarchical order?
• Figure above shows the left + operator lower than the right + operator.
This is the correct order if + operator meant to be left associative, which is
https://jntuhbtechadda.blogspot.com/
typical.
• When a grammar rule has LHS also appearing at beginning of its RHS, the
rule is said to be left recursive. The left recursion specifies left
associativity.
Extended BNF
• Because of minor inconveniences in BNF, it has been extended in several
ways. EBNF extensions do not enhance the descriptive powers of BNF;
they only increase its readability and writability.
https://jntuhbtechadda.blogspot.com/
Attribute grammars
An attribute grammar is a device used to describe more of the structure
of a programming language than can be described with a context-free grammar.
Static Semantics
• Context-free grammars (CFGs) cannot describe all of the syntax of
programming languages.
• Many static semantic rules of a language state its type constraints. Static
semantics is so named because the analysis required to these specifications
can be done at compile time.
Basic Concepts
• Attribute grammars have additions to are context-free grammars to carry
some semantic information on parse tree nodes.
https://jntuhbtechadda.blogspot.com/
Intrinsic Attributes
• Intrinsic attributes are synthesized attributes of leaf nodes whose values
are determined outside the parse tree.
The look-up function looks up a given variable name in the symbol table
and returns the variable’s type.
https://jntuhbtechadda.blogspot.com/
Computing Attribute Values
• Now, consider the process of computing the attribute values of a parse
tree, which is sometimes called decorating the parse tree.
• The tree in Figure 3.7 show the flow of attribute values in the example of
Figure 3.6.
• The tree in Figure 3.8 shows the final attribute values on the nodes. In
this example, A is defined as a real and B is defined as an int.
https://jntuhbtechadda.blogspot.com/
Describing the meanings of programs
Operational Semantics
• The idea behind operational semantics is to describe the meaning of a
statement or program, by specifying the effects of running it on a machine.
The effects on the machine are viewed as the sequence of changes in its
states, where the machine’s state is the collection of the collection of the
values in its storage.
• For example, the semantics of the C for construct can described in terms
of simpler statements, as in
https://jntuhbtechadda.blogspot.com/
• Operational semantics depends on programming languages of lower
level, not mathematics and logic.
Denotational Semantics
• Denotational semantics is the most rigorous and most widely known
formal method for describing the meaning of programs.
• A parse tree for the example binary number, 110, is show in Figure 3.9.
https://jntuhbtechadda.blogspot.com/
non-negative decimal numbers. The function Mbin is defined as follows:
Mbin ('0') = 0
Mbin ('1') = 1
Mbin (<bin_num> '0') = 2 * Mbin (<bin_num>)
Mbin (<bin_num> '1') = 2 * Mbin (<bin_num>) + 1
Axiomatic Semantics
• Axiomatic Semantics is based on mathematical logic.
• Approach: Define axioms or inference rules for each statement type in the
language (to allow transformations of expressions to other expressions.)
o The expressions are called assertions.
Assertions
• The logical expressions are called predicates, or assertions.
• An assertion before a statement (a precondition) states the relationships
and constraints among variables that are true at that point in execution.
• An assertion following a statement is a postcondition.
https://jntuhbtechadda.blogspot.com/
Weakest Preconditions
• A weakest precondition is the least restrictive precondition that will
guarantee the validity of the associated postcondition.
• The usual notation for specify the axiomatic semantic of a given statement
form is
{P} statement {Q}
where P is the precondition, Q is the postcondition, and S is the
statement form
o An example: a = b + 1 {a > 1}
One possible precondition: {b > 10}
Weakest precondition: {b > 0}
• Program proof process: The postcondition for the whole program is the
desired result. Work back through the program to the first statement. If
the precondition on the first statement is the same as the program spec,
the program is correct.
Assignment Statements
• Ex: a = b / 2 – 1 {a < 10}
The weakest precondition is computed by substituting b / 2 -1 in the
assertion {a < 10} as follows:
b / 2 – 1 < 10
b / 2 < 11
b < 22
∴ the weakest precondition for the given assignment and the postcondition is
{b < 22}
https://jntuhbtechadda.blogspot.com/
• An assignment statement has a side effect if it changes some variable other
than its left side.
Sequences
• The weakest precondition for a sequence of statements cannot be
described by an axiom, because the precondition depends on the
particular kinds of statements in the sequence.
• In this case, the precondition can only be described with an inference rule.
• Ex:
y = 3 * x + 1;
x = y + 3; {x < 10}
The weakest precondition is computed as follows:
y + 3 < 10
y<7
3*x+1<7
3*x<6
https://jntuhbtechadda.blogspot.com/
x<2
∴ the weakest precondition for the first assignment statement is {x < 2}
Selection
• We next consider the inference rule for selection statements, the general
form of which is if B then S1 else S2
We consider only selections that include else clause. The inference rule is
{B and P} S1 {Q}, {not B and P} S2 {Q}
{P} if B then S1 else S2 {Q}
https://jntuhbtechadda.blogspot.com/
UNIT-II
Names, Bindings, and Scopes:
Introduction,
names,
variables,
concept of binding,
scope,
scope and lifetime,
referencing environments,
named constants
Data types:
Introduction,
primitive,
character,
string types,
user defined ordinal types,
array,
associative arrays,
record,
tuple types,
list types,
union types,
pointer and reference types,
type checking,
strong typing,
type equivalence
Control Structures:
introduction,
selection statements,
iterative statements,
unconditional branching,
guarded commands.
https://jntuhbtechadda.blogspot.com/
Names, Bindings, and Scopes
Definitions
Variables
To indicate the storage area, each variable should be given a unique name
(identifier). Variable names are just the symbolic representation of a memory
location. For example:
char ch = 'a';
// some code
ch = 'l';
• A variable name can only have letters (both uppercase and lowercase
letters), digits and underscore.
• The first letter of a variable should be either a letter or an underscore.
• There is no rule on how long a variable name (identifier) can be. However,
you may run into problems in some compilers if the variable name is
longer than 31 characters.
Note: You should always try to give meaningful names to variables. For example:
firstName is a better variable name than fn.
Binding Times
https://jntuhbtechadda.blogspot.com/
• Language implementation time: Most language manuals leave a variety of
issues to the discretion of the language implementor. Typical examples might
be the precision (number of bits) of the fundamental types, the organization
and maximum sizes of the stack and the heap, and the handling of run-time
exceptions, such as arithmetic overflow.
• Compile time: Compiler associates names with objects, for example, a type
with a variable or the layout of a stack allocated object with a variable.
• Link time: References to functions may not be resolved until separate .o files
are compiled together. Then a placeholder reference can be replaced with an
"address" (actually an offset from a relocation register)
• Earlier binding decisions are associated with faster code (static typing),
whereas later binding decisions are associated with more flexible code
(dynamic typing, pointers point to different objects)
Scope
Scope Rules: Determine the value of a variable when it is not in the current
scope
Types of Scope
• C/C++ only have the global level and the function level.
https://jntuhbtechadda.blogspot.com/
• Some languages, like Python, Ada, or Pascal, allow functions to be nested
within other functions.
• Many languages, including Java, allow nested inner classes, which are a
form of static scoping. Each instance of an inner class can access the
environment of its enclosing classes. Each inner class maintains a static
class link to its "enclosing" object, so that at runtime the class chain can
be followed to find a reference to an enclosing instance variable. As with
static links, a fixed set of instructions can be emitted to follow the links.
https://jntuhbtechadda.blogspot.com/
• Used in older languages, like Lisp, and initially in Perl. Perl now has a
way of specifying static scope as well.
Aliasing
Definition: More than one name refers to the same object (aliasing usually is
caused by references or pointers)
• The compiler would like to store the value of *p into a register and then
assign this register value to b, without having to reload *p. However, if q
refers to the same object as p, then the register value is no longer valid.
Unless the compiler can prove that q and p can never point to the same
object, the compiler must reload the value of *p.
• In C99, you may add the restrict qualifier to a pointer declaration. This
qualifier asserts that the object to which the pointer refers has no alias in
the current scope.
https://jntuhbtechadda.blogspot.com/
Forms of operator overloading
class complex
{
double real, imaginary;
...
public:
complex operator+(complex &other)
{
return complex(real + other.real, imaginary + other.imaginary);
};
...
complex A, B, C;
C = A + B; // treated by C++ as C = A.operator+(B)
https://jntuhbtechadda.blogspot.com/
called. Notice that deep binding corresponds to an early binding of the
referencing environment and shallow binding corresponds to a late binding of
the referencing environment.
class person
{
int age;
}
int threshold;
database people;
boolean older_than_threshold(person p)
{
return p.age >= threshold;
}
void print_person(person p)
{
// call appropriate I/O routines to print person on standard output
// make use of nonlocal variable line_length to format data in columns
}
void print_selected_records(database db, procedure predicate,
print_routine)
{
int line_length;
if (device_type(stdout) == terminal)
line_length = 80
else // standard line length on older printers or files
line_length = 132
foreach person p in db do
if predicate(p)
print_routine(p)
}
main
{
threshold = 35;
print_selected_records(people, older_than_threshold, print_person);
}
shallow binding: you would probably want shallow binding for the print routine,
since you would want it to pick up the value of line_length set in
print_selected_records.
https://jntuhbtechadda.blogspot.com/
deep binding: you would probably want deep binding for threshold, since it
appears that you are trying to alter the value of threshold in main and hoping
that that value is used for older_than_threshold.
Design Considerations
• Statically scoped languages typically use deep binding, since you are
usually looking to pick up the static scope, not the dynamic scope of a
variable (note that shallow binding is essentially saying that you care
about what's on the stack when the function is called, which is what
dynamic scoping is all about)
Implementation
https://jntuhbtechadda.blogspot.com/
Returning Functions as Return Values
• Definitions
• First class value: can be returned from a function, passed as a
parameter, and assigned to variables (e.g., functions in scripting
languages, C, C++, functional languages)
Example Problem:
def plus_x(x):
return def lambda(y):
return x+y
https://jntuhbtechadda.blogspot.com/
• Mimicing the context of nested functions with object closures: In object-
oriented languages, we can encapsulate our function as a method and let
the object's fields hold context for the method. Here's a Java example for
the plus_x problem:
interface IntFunc
{
int call(int i);
}
class PlusX implements IntFunc
{
int x;
public PlusX(int n) { x = n; }
public int call(int i) { return i + x; }
}
...
IntFunc f = new PlusX(2);
System.out.println(f.call(3)); // prints 5
The interface defines an abstract type for objects enclosing a function from
integers to integers. Whereas Python would capture the value of x in a function
closure, Java captures it in an object-closure (also called a function object or
functor).
DATA TYPES
As its name indicates, a data type represents a type of the data which
you can process using your computer program. It can be numeric,
alphanumeric, decimal, etc.
https://jntuhbtechadda.blogspot.com/
o Student class "6th" has been represented by a mix of whole number
and a string of two characters. Such a mix is called alphanumeric.
o Student section has been represented by a single character which is
'J'.
o Student age has been represented by a whole number which is 13.
https://jntuhbtechadda.blogspot.com/
b) Floating - Point
A real number can hold a whole number or a fractional number that uses
a decimal point. For the value to be negative, you must place a hyphen symbol
(-) before the value. Examples of real numbers: 20.0005
2) Boolean Types
Boolean types are the simplest of all types. Their range of values has only
two elements, one for true and one for false. These data types are often used to
represent switches or flags in programs.
4) Arrays Types
An array is an aggregated of homogeneous data elements in which the
individual elements are identified by their position in the aggregate, relative to
its first element. Examples of arrays are: Character strings in C are implemented
as arrays of char. char name[ ] = "satya".
5) Pointer Types
A pointer type is one in which the variables have a range of values that
consists of memory addresses and a specific value, nil. Pointers have been
designed for two distinct kinds of uses. Pointers provide some of the addressing
flexibility of the indirect addressing that is highly used in assembly language.
And pointers provide a method of dynamic storage management . Examples of
pointers are: In C language pointers are implemented as *. int *ptr;
6) Set Types
A set type is one whose variables can store unordered collections of
distinct values from some ordinal type called its base type. The maximum
number of elements in a set is called its cardinality. Set types are often used to
model mathematical sets. Examples of set types in pascal. type colors = (red,
blue, green, yellow)
7) Union Types
A union is a type that is allowed to store different type values at different
times during program execution. Pascal introduced the concepts of integrated
discriminated unions with a record structure. Discriminated union is called a
record variant.
Characters and strings
A character type (typically called "char") may contain a single letter, digit,
punctuation mark, symbol, formatting code, control code, or some other
specialized code (e.g., a byte order mark). In C, char is defined as the smallest
https://jntuhbtechadda.blogspot.com/
addressable unit of memory. On most systems, this is 8 bits; Several standards,
such as POSIX, require it to be this size. Some languages have two or more
character types, for example a single-byte type for ASCII characters and a multi-
byte type for Unicode characters. The term "character type" is normally used
even for types whose values more precisely represent code units, for example
a UTF-16 code unit as in Java (support limited to 16-bit characters only)
and JavaScript.
Characters may be combined into strings. The string data can include
numbers and other numerical symbols but will be treated as text.
Strings are implemented in various ways, depending on the programming
language. The simplest way to implement strings is to create them as an array
of characters, followed by a delimiting character used to signal the end of the
string, usually NUL. These are referred to as null-terminated strings, and are
usually found in languages with a low amount of hardware abstraction, such
as C and Assembly. While easy to implement, null terminated strings have been
criticized for causing buffer overflows. Most high-level scripting languages, such
as Python, Ruby, and many dialects of BASIC, have no separate character type;
strings with a length of one are normally used to represent single characters.
Some languages, such as C++ and Java, have the capability to use null-
terminated strings (usually for backwards-compatibility measures), but
additionally provide their own class for string handling ( std::string and
java.lang.String , respectively) in the standard library.
https://jntuhbtechadda.blogspot.com/
Examples of string literals in C syntax are:
• "A"
• "Hello World"
a) Enumeration types
An enumeration type is one in which the user enumerates all of the
possible values, which are symbolic constants. In Ada a typical enumeration
type is shown as: type DAYS is ( M, T, W, R, F, Sa, S);
b) Subrange types
A subrange type is an ordered contiguous subsequence of an ordinal type.
These types were introduced by Pascal. For example: 12 . . . 16 is a subrange of
the integer type.
Arrays
When there is a need to use many variables then There is a big problem
because we will Conflict with name of variables So that in this Situation where
we wants to Operate on many numbers then we can use array . The Number of
Variables also increases the complexity of the Program. So that we uses Arrays.
Arrays are Set of Elements having same data type or we can Say that
Arrays are Collection of Elements having same name and same data type But
Always Remember Arrays are Always Start From its index value and the index
of array is start From 0 to n-1.
Suppose we wants to Access 5th Element of array then we will use 4th
Element Because Arrays are Start From 0 and arrays are always stored in
Continuous Memory Locations The Number of Elements and Types of array are
Identified by Subscript of array Elements. The Various types of Array those are
provided by c as follows:-
https://jntuhbtechadda.blogspot.com/
1. Single Dimensional Array
A dimensional is used representing the elements of the array for example
int a[5]
a[3]=100
This will set the value of 4th element of array. So there is only the single
bracket then it called the Single Dimensional Array.
When we talk about the Two Dimensional of the Character array The first
Subscript of the array if used for representing the Total Numbers of Strings and
the second Subscript is used for defining the length of the array Characters in
the String like This
char name[5][10]
int a[3][3][3]
https://jntuhbtechadda.blogspot.com/
In this first 3 represents the total number of Tables and the second 3
represents the total number of rows in the each table and the third 3 represents
the total number of Columns in the Tables.
So this makes the 3 Tables having the three rows and the three columns
The Main and very important thing about the array that the elements are
stored always in the Contiguous in the memory of the Computer.
There are the built in string Operation those are provided by the C
Language in the String.h Header file Like
2) strconcat: This is Used for Joining the two Strings or This function is
used for Concatenating the two Strings.
3) strRev: This Function is used for obtaining the Reverse of the String
4) strcmp: This Function is used for Comparing the Two Strings and it
gives us the Result as follows after comparing the Two Strings
it Returns us + value
it Returns us the 0
Like The array elements of Integer Types The Character array also are the
Single Dimensional or The Two Dimensional Array.
Single Dimensional Array The Single Dimensional array are used for
creating the Number of characters like
char name[10]
in this we can use the 10 characters on the name variable Means we can give
the name as 10 characters long
https://jntuhbtechadda.blogspot.com/
Associative Array
Tuple
A tuple is a compound data type having a fixed number of terms. Each
term in a tuple is known as an element. The number of elements is the size of
the tuple.
A tuple type is a comma-separated list of types, enclosed in parentheses.
You can use a tuple type as the return type of a function to enable the
function to return a single tuple containing multiple values. You can also name
the elements of a tuple type and use those names to refer to the values of the
https://jntuhbtechadda.blogspot.com/
individual elements. An element name consists of an identifier followed
immediately by a colon (:). For an example that demonstrates both of these
features, see Functions with Multiple Return Values.
using System;
public class Test
{
public static void Main()
{
var t1 = Tuple.Create(1, 2, 3, new Tuple<int, int>(4, 5));
Console.WriteLine("Tuple:" + t1);
}
}
Advantages of Tuple
Tuples offer the following advantages −
• Tuples are fined size in nature i.e. we can’t add/delete elements to/from
a tuple.
• We can search any element in a tuple.
• Tuples are faster than lists, because they have a constant set of values.
• Tuples can be used as dictionary keys, because they contain immutable
values like strings, numbers, etc.
List types
List is the most versatile data type available in functional programming
languages used to store a collection of similar data items. The concept is similar
to arrays in object-oriented programming. List items can be written in a square
bracket separated by commas. The way to writing data into a list varies from
language to language.
Union Type
A union is a special data type available in C that allows to store different
data types in the same memory location. You can define a union with many
members, but only one member can contain a value at any given time. Unions
https://jntuhbtechadda.blogspot.com/
provide an efficient way of using the same memory location for multiple-
purpose.
Defining a Union
To define a union, you must use the union statement in the same way as
you did while defining a structure. The union statement defines a new data type
with more than one member for your program. The format of the union
statement is as follows −
union Data
{
int i;
float f;
char str[20];
}
data;
https://jntuhbtechadda.blogspot.com/
name and the union member that we wish to access. You would use the
keyword union to define variables of union type.
The “pointer” and “reference” both are used to point or refer an another
variable. But, the basic difference among both of them is that a pointer variable
points to a variable whose memory location is stored in it. The reference variable
is an alias for a variable which is assigned to it.
BASIS FOR
POINTER REFERENCE
COMPARISON
Null Reference The pointer variable can refer The reference variable can
to NULL. never refer to NULL.
https://jntuhbtechadda.blogspot.com/
BASIS FOR
POINTER REFERENCE
COMPARISON
Definition of Pointer
A “pointer” is a variable that holds the memory location of another variable.
The operators used by the pointer variable is * and ->. The declaration of pointer
variable contains the base data type followed by the ‘*’ sign and the variable
name.
type *var_name;
Example
Let us understand pointer with the help of an example.
1. int a=4;
2. int * ptr= &a;
3. cout<<a; //4
4. cout<<ptr; //2007 address of varaible a
5. cout<<*ptr; //4
Here, we have an integer variable a and, a pointer variable ptr which stores
the address of variable a.
Pointer Arithmetic
The pointer variable can be operated with two arithmetic operators that
are “addition” and “subtraction”. The addition referred as “increment”, and the
subtraction is referred as “decrement”. As a pointer variable is incremented, it
points to the memory location of the next variable of its base type. As a pointer
variable is decremented, it points to the memory location of the previous variable
of its base type. Hence, an array can be efficiently accessed by a pointer variable.
Multiple Indirection
A pointer points to the other pointer variable which is pointing to the target
value. This kind of pointer is always initialized with the address of another
pointer variable. The declaration of a pointer to a pointer is as follow.
1. type **var_name;
https://jntuhbtechadda.blogspot.com/
2. int * ptr1= &a;
3. int ** ptr2= &ptr1;
4. cout<<a; //4
5. cout<<ptr1; //2007 address of varaible a
6. cout<<*ptr1; //4
7. cout<<ptr2; //1007 address of pointer variable ptr1.
8. cout<<**ptr2; //4
Function pointer
As we know that a function is not a variable, still it has a memory location,
that can be assigned to a pointer variable. Once a pointer points to a function,
then the function can be called with that function pointer.
• The pointer variable can be created without its initialization, and it can be
initialized anywhere in the program.
• The pointer variable can be reinitialized to an another variable.
• The pointer variable can refer to NULL.
Definition of Reference
The reference variable is used to refers to the variable which is assigned to
that reference variable. The operator used by the reference variable is ‘&’. The
declaration of a reference variable contains base type followed by ‘&’ sign and
then variable name.
1. type & refer_var_name = var_ name;
Here, the type is the datatype, the & operator confirms that it is a reference
variable. The refer_var_name is the name of the reference variable. The var_name
is the name of the variable, which we want the reference variable to refer.
Example
Let us understand the reference variable with the help of an example.
1. int a = 4;
2. int &b = a; // b refers to a
3. b = 6; // now a = 6
Here, the variable of type int is assigned a value 4. The reference variable
is assigned the variable a, i.e. b is alias of a. Now, when we assign another value
to b, we modify the value of a. Hence, it can be said that the changes done to a
reference variable will also occur in variable referred by that reference variable.
https://jntuhbtechadda.blogspot.com/
The most important point is that the reference variable must be initialized
at the time of its creation. Once the reference variable is initialized with a
variable, it can not be reinitialized to refer an another variable. The moment you
assign a value to a reference variable, you assign that value to a variable that a
reference variable points to. The reference variable can never refer to NULL.
Arithmetic can not be performed on a reference variable.
Note
Java does not support pointers.
Conclusion
The pointer and reference both are used to point or refer another variable. But
both differ in their usage and implementation.
https://jntuhbtechadda.blogspot.com/
Type checking
If type checking is performed at compile-time, one may speak about static
type checking; otherwise, that is, type checking is performed at run-time, a term
dynamic type checking is applied. In principle, type checking can always be
performed at run-time if the information about types of values in program is
accessible in executing code. Obviously, dynamic type checking, compared to
static one, leads to the increase of size and execution time of the object program
and lowers the reliability of the compiled code. A programming language is called
a language with static type checking or strongly typed language, if the type of
each expression can be determined at compile-time, thereby guaranteeing that
the type-related errors cannot occur in object program. Pascal is an example of
a strongly typed language. However, even for Pascal some checks can be
performed only dynamically. For instance, consider the following definitions:
table: array [0..255] of char;
i: integer;
Type checking means checking that each operation should receive proper
number of arguments and of proper data type.
Like
A=B*j+d;
* and - are basically int and float data types-based operations and if
any variable in this A=B*j+d; Is of other than int and float then compiler will
generate type error.
https://jntuhbtechadda.blogspot.com/
Two ways of Type Checking:
1) Dynamic Type Checking:
• It is done at runtime.
• It uses concept of type tag which is stored in each data objects that
indicates the data type of the object.
Example:
An integer data object contains its 'type' and 'values' attribute so Operation only
be performed after type checking sequence in which type tag of each argument
is checked. If the types are not correct then error will be generated.
• Perl and Prolog follow basically dynamically type checking because data
type of variables A+B in this case may be changed during program
execution.
https://jntuhbtechadda.blogspot.com/
2) For each variables: Name and data type of data object.
Example-
A+B
in this type of A and B variables must not be changed.
2) checked execution paths: As static type checking includes all operations that
appear in any program statement, all possible execution paths are checked,
and further testing for type error is not needed. So no type tag on data objects
at run-time are not required, and no dynamic checking is needed.
Strong Typing
If we change detect all types of errors statically in a program, we can say
that language is' strongly typed'.
Example
f:s-> R
https://jntuhbtechadda.blogspot.com/
Type infer:- In this, like in ML, the language implementation will infer any
missing type information from other declared type.
Example:
funarea(length:int, width:int):int= length *width;
This is the standard declaration which tells length and width of int data
type and its return type is int and function name area. But leaving any two of
these declarations still leaves the function will only one interpretation. Knowing
that * can multiply together either two reals or two integers. ML interprets the
following as equivalent to the previous example.
Funarea(length,width)int= length*weight;
Funarea(length:int,width)= length*weight;
Funarea(length,width:int)= length*weight;
However:
Funarea(length,width)= length*weight;
Equivalence of types
The essential part of type checking is controlling equivalence of types. It
is extremely important for a compiler to check the equivalence of types quickly.
Structural equivalence of types. Two types are called structurally equivalent, if
both are either the same primitive type, or constructed by applying the same
constructor to a structurally equivalent types. In other words, two types are
structurally equivalent if and only if they are identical. We can check whether
two types are structurally equivalent by using the following function:
bool sequiv (s, t)
{
if (s and t – two identical primitive types)
{
return true;
}
else if (s == array (s1, s2) && t == array (t1, t2))
{
return sequiv (s1, t1) && sequiv (s2, t2);
}
else if (s == s1*s2 && t == t1*t2)
{
https://jntuhbtechadda.blogspot.com/
return sequiv (s1, t1) && sequiv (s2, t2);
}
else if (s==pointer (s1) && t == pointer (t1))
{
return sequiv (s1, t1);
}
else if (s==proc (s1, s2) && t == proc (t1, t2))
{
return sequiv (s1, t1) && sequiv (s2, t2);
}
else
{
return false;
}
}
Expressions
Expressions perform the work of a program. Among other things,
expressions are used to compute and to assign values to variables and to help
control the execution flow of a program. The job of an expression is twofold: to
perform the computation indicated by the elements of the expression and to
return a value that is the result of the computation.
...
//other primitive types
char aChar = 'S';
boolean aBoolean = true;
if (Character.isUpperCase(aChar))
{
...
}
https://jntuhbtechadda.blogspot.com/
Each expression performs an operation and returns a value, as shown in
the following table.
"The largest byte value is " + Concatenate the string The resulting string:
largestByte "The largest byte value The largest byte value
is " and the value of is 127
largest Byte converted
to a string
x*y*z
x + y / 100 //ambiguous
You can specify exactly how you want an expression to be evaluated, using
balanced parentheses — ( and ). For example, to make the previous expression
unambiguous, you could write:
https://jntuhbtechadda.blogspot.com/
(x + y)/ 100 //unambiguous, recommended
If you don't explicitly indicate the order in which you want the operations
in a compound expression to be performed, the order is determined by
the precedence assigned to the operators in use within the expression. Operators
with a higher precedence get evaluated first. For example, the division operator
has a higher precedence than does the addition operator. Thus, the two following
statements are equivalent:
x + y / 100
x + (y / 100) //unambiguous, recommended
The following table shows the precedence assigned to the operators in the
Java platform. The operators in this table are listed in precedence order: The
higher in the table an operator appears, the higher its precedence. Operators
with higher precedence are evaluated before operators with a relatively lower
precedence. Operators on the same line have equal precedence. When operators
of equal precedence appear in the same expression, a rule must govern which is
evaluated first. All binary operators except for the assignment operators are
evaluated from left to right. Assignment operators are evaluated right to left.
Operator Precedence
Multiplicative */%
Additive +-
Equality == !=
https://jntuhbtechadda.blogspot.com/
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
Conditional ?:
The operands indicate what items to apply the action to. An operand can be any of the
following kinds of data items:
• Constant
• Variable
• Array element
• Function
• Substring
• Structured record field (if it evaluates to a scalar data item)
• An expression
Arithmetic Expressions
An arithmetic expression evaluates to a single arithmetic value, and its
operands have the following types. @ indicates a nonstandard feature.
• BYTE @
• COMPLEX
• COMPLEX*32 (SPARC only) @
https://jntuhbtechadda.blogspot.com/
• DOUBLE COMPLEX @
• DOUBLE PRECISION
• INTEGER
• LOGICAL
• REAL
• REAL*16 (SPARC only) @
Overloaded operators
Operator overloading is a technique by which operators used in a
programming language are implemented in user-defined types with customized
logic that is based on the types of arguments passed.
https://jntuhbtechadda.blogspot.com/
Type conversions
In computer science, type conversion or typecasting refers to changing
an entity of one datatype into another. There are two types of conversion: implicit
and explicit. The term for implicit type conversion is coercion. Explicit type
conversion in some specific way is known as casting. Explicit type conversion
can also be achieved with separately defined conversion routines such as an
overloaded object constructor.
double d;
long l;
int i;
if (d > i) d = i;
if (i > l) l = i;
if (d == l) d *= 2;
https://jntuhbtechadda.blogspot.com/
Each programming language has its own rules on how types can be
converted. In general, both objects and fundamental data types can
be converted.
== is identical to
!= is not identical to
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to
! logical negation
&& logical AND
|| logical OR
Logical operators operate on boolean variables or boolean expressions
only.
https://jntuhbtechadda.blogspot.com/
Another example:
bool isFailing;
isFailing = (examScore < 55) || (numberOfMissingHW >= 3);
// both pairs of parentheses are inserted for readability reasons only
Most C++ compilers will treat any nonzero number as true and will treat
zero as false.
The person read the code as saying: if it is not true that the score is higher
than the average, then you failed the course, otherwise you passed the course.
The above code will not cause problem during compilation, and it will also run
without run-time error. However the code actually has a mistake.
Suppose the score is 34 and the average is 63. The compiler applies the
precedence rule and interprets the Boolean expression as the following
https://jntuhbtechadda.blogspot.com/
This turns out to evaluates to false for the following reasons. First because
! is a unary logical negation operator and the value of score is nonzero and so
score is converted to true. Thus !score evaluates to false. The next operator >
compares 2 numbers and so !score is converted to 0, and then this value is
compared with 63. Since 0 is not greater than 63, the entire expression evaluates
to false, and the output will be: You passed the course.
Of course the correct way is to use parentheses and write the above
Boolean expression as follows:
C++ uses short-circuit evaluation of compound Boolean expressions for the sake
of efficiency.
The following example shows how this C++ feature can be exploited to
avoid run-time error that will occur if count happens to be zero:
Make sure you revisit this example after we cover the if statement. The NOT
operator is a unary operator. It negates a boolean variable or expression, turning
them from true to false and vice versa.
https://jntuhbtechadda.blogspot.com/
Note that if a, b, c and d are integers, for example, then
https://jntuhbtechadda.blogspot.com/
In C, when a logical operation is being evaluated, if the result is known
before all sub expressions have been evaluated, then the evaluation stops, or
short circuits. The two situations where this can occur is when the first
expression of a logical AND operation is FALSE (zero) or the first expression of a
logical OR operation is TRUE (non-zero). In both of these cases, the result is
already known. For AND, if either of the two expressions is FALSE, the result
will be FALSE. For OR, if either of the two expressions is TRUE, then the result
will be TRUE.
In most situations, this won't be a problem, but you need to be careful not
to use the results of the second expression somewhere else in your code because
there is no guarantee that it will ever be evaluated.
Assignment statements
Statements are roughly equivalent to sentences in natural languages.
A statement forms a complete unit of execution. The following types of
expressions can be made into a statement by terminating the expression with a
semicolon (;):
• Assignment expressions
• Any use of ++ or --
• Method calls
• Object creation expressions
These kinds of statements are called expression statements. Here are some
examples of expression statements:
aValue = 8933.234; //assignment statement
aValue++; //increment "
System.out.println(aValue); //method call "
Integer integerObject = new Integer(4); //object creation "
https://jntuhbtechadda.blogspot.com/
The value of a variable may be changed. For example, if x has the value
5, then the assignment statement
variable = expression;
where:
• the variable must be declared;
• the variable may be a simple name, or an indexed location in an array,
or a field (instance variable) of an object, or a static field of a class; and
• the expression must result in a value that is compatible with the type of
the variable. In other words, it must be possible to cast the expression
to the type of the variable.
Examples:
int i = 0;
price[itemNumber] = 0.80 * price[itemNumber];
myDog.name = "Fido";
Mixed-mode assignment
https://jntuhbtechadda.blogspot.com/
Control Structures
Introduction
Control Structures are just a way to specify flow of control in programs.
Any algorithm or program can be more clear and understood if they use self-
contained modules called as logic or control structures. It basically analyses and
chooses in which direction a program flows based on certain parameters or
conditions.
There are three basic types of logic, or flow of control, known as:
1. Sequence logic, or sequential flow
2. Selection logic, or conditional flow
3. Iteration logic, or repetitive flow
• Double Alternative
This structure has the form:
If (Condition), then:
[Module A]
Else:
[Module B]
[End if structure]
https://jntuhbtechadda.blogspot.com/
• Multiple Alternatives
This structure has the form:
If (condition A), then:
[Module A]
Else if (condition B), then:
[Module B]
..
..
Else if (condition N), then:
[Module N]
[End If structure]
In this way, the flow of the program depends on the set of conditions
that are written. This can be more understood by the following flow charts:
Repeat for i = A to N by I:
[Module]
[End of loop]
https://jntuhbtechadda.blogspot.com/
Here, A is the initial value, N is the end value and I is the increment.
The loop ends when A>B. K increases or decreases according to the
positive and negative value of I respectively.
Repeat-For Flow
• Repeat-While Structure
It also uses a condition to control the loop. This structure has the form:
Repeat while condition:
[Module]
[End of Loop]
https://jntuhbtechadda.blogspot.com/
In this, there requires a statement that initializes the condition
controlling the loop, and there must also be a statement inside the module
that will change this condition leading to the end of the loop.
Unconditional branching
Unconditional branching is when the programmer forces the execution of
a program to jump to another part of the program. Theoretically, this can be
done using a good combination of loops and if statements. In fact, as a
programmer, you should always try to avoid such unconditional branching and
use this technique only when it is very difficult to use a loop.
Syntax
The syntax for a goto statement in C is as follows −
goto label;
..
.
label: statement;
Here label can be any plain text except C keyword and it can be set anywhere
in the C program above or below to goto statement.
https://jntuhbtechadda.blogspot.com/
Flow Diagram
Example
#include <stdio.h>
int main () {
/* local variable definition */
int a = 10;
/* do loop execution */
LOOP:do {
if( a == 15) {
/* skip the iteration */
a = a + 1;
goto LOOP;
}
printf("value of a: %d\n", a);
a++;
}
while( a < 20 );
return 0;
}
https://jntuhbtechadda.blogspot.com/
When the above code is compiled and executed, it produces the following result−
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Guarded commands
https://jntuhbtechadda.blogspot.com/
UNIT-III
Subprograms:
Fundamentals of subprograms,
design issues for subprograms,
local referencing environments,
parameter passing methods,
parameters that are subprograms,
calling subprograms indirectly,
overloaded subprograms,
generic subprograms,
design issues for functions,
user defined overloaded operators,
closures,
co routines
Implementing subprograms:
General semantics of calls and returns,
implementing simple subprograms,
implementing subprograms with stack-dynamic local variables,
nested subprograms,
blocks,
implementing dynamic scoping
Subprograms
A Subprogram is a program inside any larger program that can be reused
any number of times.
Characteristics of a Subprogram:
• A Subprogram is implemented using the Call & Return instructions in
Assembly Language.
• The Call Instruction is present in the Main Program and the Return(Ret)
Instruction is present in the subprogram itself.
https://jntuhbtechadda.blogspot.com/
• It is important to note that the Main Program is suspended during the
execution of any subprogram. Moreover, after the completion of the
subprogram the main program executes from the next sequential address
present in the Program Counter.
https://jntuhbtechadda.blogspot.com/
A subprogram is a sequence of instructions whose execution is invoked
from one or more remote locations in a program, with the expectation that when
the subprogram execution is complete, execution resumes at the instruction
after the one that invoked the subprogram. In high-level languages,
subprograms are also called subroutines, procedures, and functions. In object-
oriented languages, they are usually called methods or constructors. In most
modern high-level languages, subprograms can have parameters, local
variables, and returned values.
Basic Definitions
• A subprogram definition is a description of the actions of the subprogram
abstraction.
• A subprogram call is an explicit request that the called subprogram be
executed.
https://jntuhbtechadda.blogspot.com/
• A subprogram is said to be active if, after having been called, it has begun
execution but has not yet completed that execution.
Parameters
• Subprograms typically describe computations. There are two ways that a
non-local method program can gain access to the data that it is to process:
1. Through direct access to non-local variables.
https://jntuhbtechadda.blogspot.com/
• The only way the computation can proceed on different data is to
assign new values to those non-local variables between calls to the
subprograms.
• Extensive access to non-locals can reduce reliability.
2. Through parameter passing “more flexible”.
• Data passed through parameters are accessed through names that are
local to the subprogram.
• A subprogram with parameter access to the data it is to process is a
parameterized computation.
• It can perform its computation on whatever data it receives through its
parameters.
• A formal parameter is a dummy variable listed in the subprogram header
and used in the subprogram.
• Subprograms call statements must include the name of the subprogram and
a list of parameters to be bound to the formal parameters of the subprogram.
• An actual parameter represents a value or address used in the subprogram
call statement.
• Actual/Formal Parameter Correspondence:
1. Positional: The first actual parameter is bound to the first formal
parameter and so forth. “Practical if list is short.”
2. Keyword: the name of the formal parameter is to be bound with the
actual parameter. “Can appear in any order in the actual parameter list.”
SORT(LIST => A, LENGTH => N);
• Advantage: order is irrelevant
• Disadvantage: user must know the formal parameter’s names.
• Default Values:
procedure SORT(LIST : LIST_TYPE;
LENGTH : INTEGER := 100);
...
SORT(LIST => A);
• In C++, which has no keyword parameters, the rules for default parameters
are necessarily different.
• The default parameters must appear last, for parameters are positionally
associated.
• Once a default parameter is omitted in a call, all remaining formal
parameters must have default values.
float compute_pay(float income, float tax_rate,
int exemptions = 1)
https://jntuhbtechadda.blogspot.com/
Procedures and Functions
• There are two distinct categories of subprograms, procedures and
functions.
• Procedures: provide user-defined parameterized computation statements.
• The computations are enacted by single call statements.
• Procedures can produce results in the calling program unit by two
methods:
o If there are variables that are not formal parameters but are still
visible in both the procedure and the calling program unit, the
procedure can change them.
o If the subprogram has formal parameters that allow the transfer of
data to the caller, those parameters can be changed.
• Functions: provide user-defined operators which are semantically
modelled on mathematical functions.
o If a function is a faithful model, it produces no side effects.
o It modifies neither its parameters nor any variables defined outside
the function.
• The methods of Java, C++, and C# are syntactically similar to the
functions of C.
https://jntuhbtechadda.blogspot.com/
Local Referencing Environments
• Vars that are defined inside subprograms are called local vars.
• Local vars can be either static or stack dynamic “bound to storage when
the program begins execution and are unbound when execution
terminates.”
• Advantages of using stack dynamic:
a. Support for recursion.
b. Storage for locals is shared among some subprograms.
• Disadvantages:
a. Allocation/deallocation time.
b. Indirect addressing “only determined during execution.”
c. Subprograms cannot be history sensitive “can’t retain data values of
local vars between calls.”
• Advantages of using static vars:
a. Static local vars can be accessed faster because there is no indirection.
b. No run-time overhead for allocation and deallocation.
c. Allow subprograms to be history sensitive.
• Disadvantages:
a. Inability to support recursion.
b. Their storage can’t be shared with the local vars of other inactive
subprograms.
• In C functions, locals are stack-dynamic unless specifically declared to be
static.
• Ex:
int adder(int list[ ], int listlen)
{
static int sum = 0; //sum is static variable
int count; //count is stack-dynamic
for (count = 0; count < listlen; count++)
sum += list[count];
return sum;
}
• Ada subprograms and the methods of C++, Java, and C# have only stack
dynamic local variables.
https://jntuhbtechadda.blogspot.com/
• There are two conceptual models of how data transfers take places in
parameter transmission:
o Either an actual value is copied (to the caller, to the callee, or both
ways), or
o An access path is transmitted.
• Most commonly, the access path is a simple pointer or reference.
• Figure below illustrates the three semantics of parameter passing when
values are copied.
2. Pass-by-Result
• Pass-by-Result is an implementation model for out-mode parameters.
• When a parameter is passed by result, no value is transmitted to the
subprogram.
• The corresponding formal parameter acts as a local var, but just before
control is transferred back to the caller, its value is transmitted back to
the caller’s actual parameter, which must be a var.
• One problem with the pass-by-result model is that there can be an actual
parameter collision, such as the one created with the call.
https://jntuhbtechadda.blogspot.com/
sub(p1, p1)
• In sub, assuming that the two formal parameters have different names,
the two can obviously be assigned different values.
• Then whichever of the two is copied to their corresponding actual
parameter last becomes the value of p1.
3. Pass-by-Value-Result
• It is an implementation model for inout-mode parameters in which actual
values are copied.
• It is a combination of pass-by-value and pass-by-result.
• The value of the actual parameter is used to initialize the corresponding
formal parameter, which then acts as a local var.
At subprogram termination, the value of the formal parameter is
transmitted back to the actual parameter.
• It is sometimes called pass-by-copy because the actual parameter is
copied to the formal parameter at subprogram entry and then copied back
at subprogram termination.
4. Pass-by-reference
• Pass-by-reference is a second implementation model for inout-mode
parameters.
• Rather than copying data values back and forth. This method transmits
an access path, sometimes just an address, to the called subprogram. This
provides the access path to the cell storing the actual parameter.
• The actual parameter is shared with the called subprogram.
• Advantages:
The passing process is efficient in terms of time and space.
Duplicate space is not required, nor is any copying.
• Disadvantages:
Access to the formal parameters will be slower than pass-by-value,
because of additional level of indirect addressing that is required.
• Inadvertent and erroneous changes may be made to the actual parameter.
• Aliases can be created as in C++.
void fun(int &first, int &second)
If the call to fun happens to pass the same var twice, as in
fun(total, total)
Then first and second in fun will be aliases.
5. Pass-by-Name
• The method is an inout-mode parameter transmission that doesn’t
correspond to a single implementation model.
• When parameters are passed by name, the actual parameter is, in effect,
textually substituted for the corresponding formal parameter in all its
occurrences in the subprogram.
https://jntuhbtechadda.blogspot.com/
• A formal parameter is bound to an access method at the time of the
subprogram call, but the actual binding to a value or an address is delayed
until the formal parameter is assigned or referenced.
• Because pass-by-name is not used in any widely used language, it is not
discussed further here.
https://jntuhbtechadda.blogspot.com/
Type-Checking Parameters
• It is now widely accepted that software reliability demands that the types
of actual parameters be checked for consistency with the types of the
corresponding formal parameters.
• Ex:
result = sub1(1)
• The actual parameter is an integer constant. If the formal parameter of
sub1 is a floating-point type, no error will be detected without parameter
type checking.
• Early languages, such as Fortran 77 and the original version of C, did not
require parameter type checking.
• Pascal, FORTRAN 90, Java, and Ada: it is always required
• Perl, PHP, and JavaScript do not have type checking.
https://jntuhbtechadda.blogspot.com/
• Figure below illustrates the previous parameters’ passing methods.
• The subprogram sub is called from main with the call sub(w, x ,y, z), where
w is passed by value, x is passed by result, y is passed by value-result,
and z is passed by reference.
• A subtle but fatal error can occur with pass-by-reference and pass-by-
value-result parameters if care is not take in their implementation.
• Suppose a program contains two references to the constant 10, the first
as an actual parameter in a call to a subprogram.
• Further suppose that the subprogram mistakenly changes the formal
parameter that corresponds to the 10 to the value 5.
• The compiler may have built a single location for the value 10 during
compilation, as compilers often do, and use that location for all references
to the constant 10 in the program.
• But after the return from the subprogram, all subsequent occurrences of
10 will actually be references to the value 5.
• If this is allowed to happen, it creates a programming problem that is very
difficult to diagnose.
• This happened in many implementations of Fortran IV.
https://jntuhbtechadda.blogspot.com/
• The question is what referencing environment for executing the passed
subprogram should be used.
• The three choices are:
1. It is the environment of the call statement that enacts the passed
subprogram “Shallow binding.”
2. It is the environment of the definition of the passed subprogram “Deep
binding.”
3. It is the environment of the call statement that passed the subprogram
as an actual parameter ”Ad hoc binding; has never been used”
• Ex: “written in the syntax of Java”
function sub1( )
{
var x;
function sub2( )
{
alert(x); // Creates a dialog box with the value of x
};
function sub3( )
{
var x;
x = 3;
sub4(sub2);
};
function sub4(subx )
{
var x;
x = 4;
subx( );
};
x = 1;
sub3( );
};
• Consider the execution of sub2 when it is called in sub4.
• Shallow Binding: the referencing environment of that execution is that of
sub4, so the reference to x in sub2 is bound to the local x in sub4, and
the output of the program is 4.
• Deep Binding: the referencing environment of sub2’s execution is that of
sub1, so the reference so the reference to x in sub2 is bound to the local
x in sub1 and the output is 1.
• Ad hoc: the binding is to the local x in sub3, and the output is 3.
• Shallow binding is not appropriate for static-scoped languages with nested
subprograms.
https://jntuhbtechadda.blogspot.com/
Overloaded Subprograms
• An overloaded operator is one that has multiple meanings. The types of its
operands determine the meaning of a particular instance of an overloaded
operator.
• For example, if the * operator has two floating-point operands in a Java
program, it specifies floating-point multiplication.
• But if the same operator has two integer operands, it specifies integer
multiplication.
• An overloaded subprogram is a subprogram that has the same name as
another subprogram in the same referencing environment.
• Every version of an overloaded subprogram must have a unique protocol;
that is, it must be different from the others in the number, order, or types
of its parameters, or in its return if it is a function.
• The meaning of a call to an overloaded subprogram is determined by the
actual parameter list.
• Users are also allowed to write multiple versions of subprograms with the
same name in Ada, Java, C++, and C#.
• Overloaded subprograms that have default parameters can lead to
ambiguous subprogram calls.
void fun(float b = 0.0);
void fun( );
…
fun( ); // The call is ambiguous and will cause a compilation error.
Generic Subprograms
• A programmer should not need to write four different sort subprograms to
sort four arrays that differ only in element type.
• A generic or polymorphic subprogram takes parameters of different types
on different activations.
• Overloaded subprograms provide a particular kind of polymorphism called
ad hoc polymorphism.
• Parametric polymorphism is provided by a subprogram that takes a
generic parameter that is used in a type expression that describes the
types of the parameters of the subprogram.
https://jntuhbtechadda.blogspot.com/
for (top = 0, top < len –2; top ++)
for (bottom = top + 1; bottom < len – 1; bottom++)
if (list [top] > list [bottom])
{
temp = list [top];
list[top] = list[bottom];
}
} // end for bottom
} // end for generic
}
• The instantiation of this template function is:
float flt_list [100];
…
generic_sort (flt_list, 100);
https://jntuhbtechadda.blogspot.com/
Sum: Integer := 0;
begin
for Index in A’range loop
Sum := Sum + A(Index) * B(Index)
end loop
return sum;
end “*”;
…
c = a * b; -- a, b, and c are of type Vec_Type
Coroutines
• A coroutine is a subprogram that has multiple entries and controls them
itself.
• It is also called symmetric control.
• It also has the means to maintain their status between activation.
• This means that coroutines must be history sensitive and thus have static
local vars.
• Secondary executions of a coroutine often begin at points other than its
beginning.
• A coroutine call is named a resume.
• The first resume of a coroutine is to its beginning, but subsequent calls
enter at the point just after the last executed statement in the coroutine.
https://jntuhbtechadda.blogspot.com/
Implementing subprograms
https://jntuhbtechadda.blogspot.com/
• Return Semantics:
- If pass-by-value-result or out mode parameters are used, move the
current values of those parameters to their corresponding actual
parameters (arguments).
- If it is a function, move the functional value to a place the caller can
get it.
- Restore the execution status of the caller.
- Transfer control back to the caller.
• Required storage:
- Status information, parameters, return address, return value for
functions.
• Two separate parts:
- the actual code (that cannot change).
- and the non-code part (local variables and data that can change).
• The format, or layout, of the non-code part of an executing subprogram is
called an activation Record.
• An activation record instance is a concrete example of an activation record
(the collection of data for a particular subprogram activation).
https://jntuhbtechadda.blogspot.com/
Implementing Subprograms with Stack-Dynamic Local Variables
• More complex activation record
- The compiler must generate code to cause implicit allocation and
deallocation of local variables.
- Recursion must be supported (adds the possibility of multiple
simultaneous activations of a subprogram).
https://jntuhbtechadda.blogspot.com/
More Complex Activation Records
• The activation record format is static, but its size may be dynamic.
• The dynamic link points to the top of an instance of the activation record
of the caller.
• An activation record instance is dynamically created when a subprogram
is called.
• Activation record instances reside on the run-time stack.
• The Environment Pointer (EP) must be maintained by the run-time
system. It always points at the base of the activation record instance of
the currently executing program unit.
• An Example: C Function
void sub(float total, int part)
{
int list[5];
float sum;
...
}
https://jntuhbtechadda.blogspot.com/
The caller actions are as follows:
1. Create an activation record instance.
2. Save the execution status of the current program unit.
3. Compute and pass arguments.
4. Record the return address for the callee.
5. Transfer control to the callee.
Nested Subprograms
• Some non-C-based static-scoped languages (e.g., Fortran 95, Ada,
Python, JavaScript, Ruby, and Lua) use stack-dynamic local variables
and allow subprograms to be nested.
• All variables that can be non-locally accessed reside in some activation
record instance in the stack.
• The process of locating a non-local reference:
1. Find the correct activation record instance
2. Determine the correct offset within that activation record instance
• Locating a Non-local Reference
– Finding the offset is easy
– Finding the correct activation record instance
• Static semantic rules guarantee that all non-local variables that can be
referenced have been allocated in some activation record instance that is
on the stack when the reference is made.
• Static Scoping
– A static chain is a chain of static links that connects certain activation
record instances.
– The static link in an activation record instance for subprogram A points
to one of the activation record instances of A's static parent.
https://jntuhbtechadda.blogspot.com/
– The static chain from an activation record instance connects it to all of
its static ancestors.
– Static_depth is an integer associated with a static scope whose value is
the depth of nesting of that scope.
– The chain_offset or nesting_depth of a nonlocal reference is the difference
between the static_depth of the reference and that of the scope when it is
declared.
– A reference to a variable can be represented by the pair:
(chain_offset, local_offset),
where local_offset is the offset in the activation record of the
variable being referenced.
• Displays
- An alternative to static chains that solves the problems with that
approach.
- Static links are stored in a single array called a display.
- The contents of the display at any given time is a list of addresses
of the accessible activation record instances.
Blocks
• Blocks are user-specified local scopes for variables
• An example in C
{
int temp;
temp = list [upper];
list [upper] = list [lower];
list [lower] = temp;
https://jntuhbtechadda.blogspot.com/
}
• The lifetime of temp in the above example begins when control enters the
block.
• An advantage of using a local variable like temp is that it cannot interfere
with any other variable with the same name.
• Implementing Blocks
- Two Methods:
1. Treat blocks as parameter-less subprograms that are always
called from the same location.
- Every block has an activation record; an instance is created
every time the block is executed.
2. Since the maximum storage required for a block can be statically
determined, this amount of space can be allocated after the local
variables in the activation record.
Dynamic scoping does not care how the code is written, but instead how
it executes. Each time a new function is executed, a new scope is pushed onto
the stack. This scope is typically stored with the function’s call stack. When a
variable is referenced in the function, the scope in each call stack is checked to
see if it provides the value
We can implement dynamic scoping fairly easily in Lua through the debug
library. We'll mimic the example above with a function called dynamic that takes
the name of a variable, as a string, to look up dynamically.
https://jntuhbtechadda.blogspot.com/
The return value of this function is either nil if nothing was found, or the
name and value of the variable.
As a software engineer, you should know these terms, because you will
run into them frequently. The fundamental purpose of all of these ideas is to
help achieve the three important properties that we care about in 6.005: safety
from bugs, ease of understanding, and readiness for change.
https://jntuhbtechadda.blogspot.com/
• mutators: none (it’s immutable)
List is Java’s list interface. List is mutable. List is also an interface, which means
that other classes provide the actual implementation of the data type. These
classes include ArrayList and LinkedList.
• creators: ArrayList and LinkedList constructors, Collections.singletonList
• producers: Collections.unmodifiableList
• observers: size, get
• mutators: add, remove, addAll, Collections.sort
This classification gives some useful terminology, but it’s not perfect. In
complicated data types, there may be an operation that is both a producer and
a mutator, for example. Some people reserve the term producer only for
operations that do no mutation.
https://jntuhbtechadda.blogspot.com/
But it should not mix generic and domain-specific features. A Deck type
intended to represent a sequence of playing cards shouldn’t have a generic add
method that accepts arbitrary objects like ints or Strings. Conversely, it wouldn’t
make sense to put a domain-specific method like dealCards into the generic type
List.
Design Issues
• What is the form of the container for the interface to the type?
• Can abstract types be parameterized?
• What access controls are provided?
Language Examples
https://jntuhbtechadda.blogspot.com/
2. Abstract Data Types in C++
• Constructors:
o Functions to initialize the data members of instances (they do not
create the objects)
o May also allocate storage if part of the object is heap-dynamic
o Can include parameters to provide parameterization of the objects
o Implicitly called when an instance is created
o Can be explicitly called
o Name is the same as the class name
• Destructors
o Functions to cleanup after an instance is destroyed; usually just to
reclaim heap storage
o Implicitly called when the object’s lifetime ends
o Can be explicitly called
o Name is the class name, preceded by a tilde (~)
https://jntuhbtechadda.blogspot.com/
4. Abstract Data Types in C#
• Class members can be marked private or public, with public being the
default
• Classes are dynamic
• Parameterized ADTs allow designing an ADT that can store any type
elements (among other things) – only an issue for static typed languages
• Also known as generic classes
• C++, Ada, Java 5.0, and C# 2005 provide support for parameterized ADTs
1. Ada
https://jntuhbtechadda.blogspot.com/
o Make the stack type more flexible by making the element type and
the size of the stack generic
generic
Max_Size: Positive;
type Elem_Type is private;
package Generic_Stack is
Type Stack_Type is limited private;
function Top(Stk: in out StackType) return Elem_type;
…
end Generic_Stack;
Package Integer_Stack is new Generic_Stack(100,Integer);
Package Float_Stack is new Generic_Stack(100,Float);
2. C++
class Stack
{
…
Stack (int size)
{ stk_ptr = new int [size];
max_len = size - 1;
top = -1;
};
…
}
Stack stk(100);
3. Java 5.0
https://jntuhbtechadda.blogspot.com/
Integer myInt=(Integer)myArray.get(0);
– Java 5.0
ArrayList <Integer> myArray =new ArrayList <Integer>();
4. C# 2005
Encapsulation Constructs
1. Introduction
2. Nested Subprograms
3. Encapsulation in C
4. Encapsulation in C++
https://jntuhbtechadda.blogspot.com/
o The member definitions are defined in a separate file
• Friends provide a way to grant access to private members of a class
5. Ada Packages
Naming Encapsulations
• Large programs define many global names need a way to divide into logical
groupings
• A naming encapsulation is used to create a new scope for names
1. C++ Namespaces
• Can place each library in its own namespace and qualify names used
outside with the namespace
• C# also includes namespaces
2. Java Packages
• Packages can contain more than one class definition; classes in a package
are partial friends
• Clients of a package can use fully qualified name or use the import
declaration
3. Ada Packages
4. Ruby Modules
• Ruby classes are name encapsulations, but Ruby also has modules
• Typically encapsulate collections of constants and methods
• Modules cannot be instantiated or subclassed, and they cannot define
variables
• Methods defined in a module must include the module’s name
• Access to the contents of a module is requested with the require method
https://jntuhbtechadda.blogspot.com/
UNIT-IV Concurrency: introduction, introduction to subprogram level
concurrency, semaphores, monitors, message passing, Ada support for
concurrency, Java threads, concurrency in functional languages, statement level
concurrency. Exception Handling and Event Handling: Introduction, exception
handling in Ada, C++, Java, introduction to event handling, event handling with
Java and C#.
Concurrency:
Concurrency in software execution can occur at four different levels: instruction level
(executing two or more machine instructions simultaneously), statement level
(executing two or more high-level language statements simultaneously), unit level
(executing two or more subprogram units simultaneously), and program level
(executing two or more programs simultaneously).
Multiprocessor Architectures:
•
Late 1950s - one general-purpose processor and one or more special-purpose
processors for input and output operations
• Early 1960s - multiple complete processors, used for program-level
concurrency
• Mid-1960s - multiple partial processors, used for instruction-level concurrency
• Single-Instruction Multiple-Data (SIMD) machines
• Multiple-Instruction Multiple-Data (MIMD) machines
– Independent processors that can be synchronized (unit-level
concurrency)
Categories of Concurrency:
There are two distinct categories of concurrent unit control. The most natural category
of concurrency is that in which, assuming that more than one processor is available,
several program units from the same program literally execute simultaneously. This is
physical concurrency. A slight relaxation of this concept of concurrency allows the
programmer and the application software to assume that there are multiple processors
providing actual concurrency, when in fact the actual execution of programs is taking
place in interleaved fashion on a single processor. This is logical concurrency.
One useful technique for visualizing the flow of execution through a program is to
imagine a thread laid on the statements of the source text of the program.
Every statement reached on a particular execution is covered by the thread
representing that execution.
Formally, a thread of control in a program is the sequence of program points reached
as control flows through the program.
Programs that have coroutines but no concurrent subprograms, though they are
sometimes called quasi-concurrent, have a single thread of control. Programs
executed with physical concurrency can have multiple threads of control.
program designed to have more than one thread of control is said to be multithreaded.
Synchronization is a mechanism that controls the order in which tasks execute. Two
kinds of synchronization are required when tasks share data: cooperation and
competition. Cooperation synchronization is required between task A and task B
when task A must wait for task B to complete some specific activity before task A can
begin or continue its execution. Competition synchronization is required between two
tasks when both require the use of some resource that cannot be simultaneously used..
A simple form of cooperation synchronization can be illustrated by a common
problem called the producer-consumer problem.
• Cooperation: Task A must wait for task B to complete some specific activity
before task A can continue its execution, e.g., the producer-consumer problem
• Competition: Two or more tasks must use some resource that cannot be
simultaneously used, e.g., a shared counter
– Competition is usually provided by mutually exclusive access
Scheduler
•
Providing synchronization requires a mechanism for delaying task execution
•
Task execution control is maintained by a program called the scheduler, which
maps task execution onto available processors
Task Execution States
Semaphores
Cooperation Synchronization
Competition Synchronization
Monitors
One solution to some of the problems of semaphores in a concurrent environment is to
encapsulate shared data structures with their operations and hide their
representations—that is, to make shared data structures abstract data types with some
special restrictions.
Cooperation Synchronization
Mutually exclusive access to shared data is intrinsic with a monitor, cooperation
between processes is still the task of the programmer.
Different languages provide different ways of programming cooperation
synchronization, all of which are related to semaphores.
EVALUATION OF MONITORS:
MESSAGE PASSING
- A way to remember who is waiting to have its message accepted and some “fair”
way of choosing the next message
• When a sender task’s message is accepted by a receiver task, the actual
message transmission is called a rendezvous
task Task_Example is
entry ENTRY_1 (Item : in Integer);
end Task_Example;
Task Body
• The body task describes the action that takes place when a rendezvous occurs
• A task that sends a message is suspended while waiting for the message to be
accepted and during the rendezvous
• Entry points in the spec are described with accept clauses in the body
Example:
Concurrency in Ada 95
• A block or subprogram is not left until all of its dependent tasks are terminated
• Ada 95 includes Ada 83 features for concurrency, plus two new features
• Protected objects: A more efficient way of implementing shared data to
allow access to a shared data structure to be done without rendezvous
• Asynchronous communication
•
A protected object is similar to an abstract data type
•
Access to a protected object is either through messages passed to entries, as
with a task, or through protected subprograms
• A protected procedure provides mutually exclusive read-write access to
protected objects
• A protected function provides concurrent read-only access to protected objects
Asynchronous Communication
JAVA THREADS
The concurrent units in Java are methods named run, whose code can be in concurrent
execution with other such methods (of other objects) and with the main method.
The process in which the run methods execute is called a thread.
Java’s threads are lightweight tasks, which means that they all run in the same address
space.
•
The Thread class has several methods to control the execution of threads
– The yield is a request from the running thread to voluntarily surrender
the processor
– The sleep method can be used by the caller of the method to block the
thread
– The join method is used to force a method to delay its execution until
the run method of another thread has completed its execution
Thread Priorities
• A thread’s default priority is the same as the thread that create it
– If main creates a thread, its default priority is NORM_PRIORITY
• Threads defined two other priority constants, MAX_PRIORITY and
MIN_PRIORITY
• The priority of a thread can be changed with the methods setPriority
Competition Synchronization with Java Threads
• A method that includes the synchronized modifier disallows any other method
from running on the object while it is in execution
…
public synchronized void deposit( int i) {…}
public synchronized int fetch() {…}
…
• The above two methods are synchronized which prevents them from
interfering with each other
• If only a part of a method must be run without interference, it can be
synchronized thru synchronized statement
synchronized (expression)
statement
C# THREADS
Synchronizing Threads
An exception is raised when its associated event occurs. In some C-based languages,
exceptions are said to be thrown, rather than raised.
Different kinds of exceptions require different exception handlers. Detection of end-
of-file nearly always requires some specific program action.
Design Issues
• How and where are exception handlers specified and what is their scope?
• How is an exception occurrence bound to an exception handler?
• Handler form:
when exception_choice{|exception_choice} => statement_sequence
...
[when others =>
statement_sequence]
exception_choice form:
• If the block or unit in which an exception is raised does not have a handler for
that exception, the exception is propagated elsewhere to be handled
– Procedures - propagate it to the caller
– Blocks - propagate it to the scope in which it appears
– Package body - propagate it to the declaration part of the unit that
declared the package (if it is a library unit, the program is terminated)
– Task - no propagation; if it has a handler, execute it; in either case,
mark it "completed"
Continuation
• The block or unit that raises an exception but does not handle it is always
terminated (also any block or unit to which it is propagated that does not
handle it)
•
User-defined Exceptions form:
exception_name_list : exception;
• Raising Exceptions form:
raise [exception_name]
– (the exception name is not required if it is in a
handler--in this case, it propagates the same
exception)
– Exception conditions can be disabled with:
pragma SUPPRESS(exception_list)
PREDEFINED EXCEPTIONS:
The exception handling of C++ was accepted by the ANSI C++ standardization
committee in 1990 and subsequently found its way into C++ implementations. The
design is based in part on the exception handling of CLU, Ada, and ML. One major
Throwing Exceptions
Unhandled Exceptions
Continuation
•
After a handler completes its execution, control flows to the first statement
after the last handler in the sequence of handlers of which it is an element
• Other design choices
– All exceptions are user-defined
– Exceptions are neither specified nor declared
– The default handler, unexpected, simply terminates the program;
unexpected can be redefined by the user
– Functions can list the exceptions they may raise
– Without a specification, a function can raise any exception (the throw
clause)
Evaluation
• It is odd that exceptions are not named and that hardware- and system
software-detectable exceptions cannot be handled
• Binding exceptions to handlers through the type of the parameter certainly
does not promote readability
Classes of Exceptions
Continuation:
• The Java throws clause is quite different from the throw clause of C++
• Exceptions of class Error and RunTimeException and all of their descendants
are called unchecked exceptions; all other exceptions are called checked
exceptions
• Checked exceptions that may be thrown by a method must be either:
– Listed in the throws clause, or
– Handled in the method
Event handling is similar to exception handling. In both cases, the handlers are
implicitly called by the occurrence of something, either an exception or an event.
While exceptions can be created either explicitly by user code or implicitly by
hardware or a software interpreter, events are created by external actions, such as user
interactions through a graphical user interface (GUI).
Another common use of event handlers is to check for simple errors and omissions in
the elements of a form, either when they are changed or when the form is submitted to
the Web server for processing.
Using event handling on the browser to check the validity of form data saves the time
of sending that data to the server, where their correctness then must be checked by a
server-resident program or script before they can be processed. This kind of event-
driven programming is often done using a client-side scripting language, such as
JavaScript.
• User interactions with GUI components create events that can be caught by
event handlers, called event listeners
• An event generator tells a listener of an event by sending a message
• An interface is used to make event-handling methods conform to a standard
protocol
• A class that implements a listener must implement an interface for the listener
• One class of events is ItemEvent, which is associated with the event of
clicking a checkbox, a radio button, or a list item
• The ItemListener interface prescribes a method, itemStateChanged, which is a
handler for ItemEvent events
Event Handling in C#
Event handling in C# (and in the other .NET languages) is similar to that of Java.
.NET provides two approaches to creating GUIs in applications, the original Windows
Forms and the more recent Windows Presentation Foundation.
All C# event handlers have the same protocol: the return type is void and the two
parameters are of types object and EventArgs.
Functional programming languages are modeled on mathematical functions i.e all the
computations can be done by applying mathematical functions to the specified
parameters.
MATHEMATICAL FUNCTIONS
A mathematical function is a mapping of members of one set, called the domain set,
to another set, called the range set. A function definition specifies the domain and
range sets, either explicitly or implicitly, along with the mapping. The mapping is
described by an expression or, in some cases, by a table.
1. In FPLs the programmers are not concerned with the variables because the
memory cells are not conceptualized into the language.
2. Less labour is required for constructing the programs
3. They have simple syntactic and semantic structures.
4. Concurrent program execution is easy to understand , design and use.
5. Programmer is not concerned with the cooperation synchronization and
dynamic division of the programs.
DISADVANTAGES:
Simple Functions
Function definitions are often written as a function name, followed by a list of
parameters in parentheses, followed by the mapping expression. For example,
cube(x) ≡ x * x * x, where x is a real number In this definition, the domain and range
sets are the real numbers. The symbol ≡ is used to mean “is defined as.” The
parameter x can represent any member of the domain set, but it is fixed to represent
one specific element during evaluation of the function expression.
A method called as the Lambda notation is used for nameless functions. A
Lambda expression is a function that represents the parameter and function
mapping.
λ(x) x * x
A lambda Calculus is defined as a formal computation model using lambda
expressions. Lambda calculus can be either typed or un-typed.
Function Forms:
A higher-order function, or functional form, is one that either takes one or more
functions as parameters or yields a function as its result, or both. One common kind of
functional form is function composition, which has two functional parameters and
yields a function whose value is the first actual parameter function applied to the
result of the second.
FUNDAMENTAL OF FPL
The objective of the design of a functional programming language is to imitate
mathematical functions to the greatest extent possible. This results in an approach to
problem solving that is fundamentally different from approaches used with imperative
languages. In an imperative language, an expression is evaluated and the result is
stored in a memory location, which is represented as a variable in a program. This is
the purpose of assignment statements. This necessary attention to memory cells,
There are two primitive types available in LISP they are atoms and lists.
Atom in lisp referred to the most fundamental basic data type. There are two types of
atoms they are
1. A literal atom that represents symbols
2. A numeric atom which represents numbers
Lists are widely used in list processing. LISP was originally used in lists as its data
structure because they were though to be an essential part of list processing. Two
types of lists are
1. Simple List which does not contain any sub lists
2. Nested List which contain sub lists specified in the inner parenthesis.
An Integer, Float or the hardware representation used for the numbers in LISP.
Strings
Strings are expressed as string of symbols.
mkvect(bound)
A datatype of type vector is created by this function whose script ranges from 0 to a
given bound. Each vector component contains a pointer to the LISP data object which
are initially set to nil.
getv(vector,subscript)
A pointer stored at a specified subscript in the argument vector is returned by this
function.
putv
It is used to assign a new value to a particular vector component
COND Semantics
Syntax:
LET Semantics
LET binds the parameters specified with in the expression. The LET expression
computes the initial value before binding the values.
Syntax:
LET<bindings><body>
LISP INTREPRETER
The computation theory deals with the process of computations using a model. A
universal computing machine resembles universal turing machine and is constructed
to simulate all other machines present in the model. Based on this concept a universal
LISP function that can compute any LISP function has been constructed.
For Constructing universal LISP functions the fundamental requirement is that it must
allow functions to be represented in the same way in which data is represented. As
parenthesized list notation is used for representing LISP data the function definitions
and function calls are also expressed in list notation.
An interpreter for LISP can be written in LISP. Such an interpreter, which is not a
large program, describes the operational semantics of LISP, in LISP.
The Cambridge polish notation denotes a prefix notation for describing the LISP
function call as follows
(function_name(LAMBDA(arg_1…arg_n)expr))
The factorial of a given number n in LISP can be determined using defun keyword.
The function definition is as follows
(defun (factorial n)
(if(=n 0)
1
(*n factorial (-n 1)))
))
The above factorial function returns 1 if the entered number n is 1 else it makes a
recursive call to the factorial function to compute the factorial of a given number.
Fibonacci Number
(defun fib(n)
(if (or (=n 0) (=n 1))
1
(+(fib(-n 1))(fib(-n 2)))))
Initially if(n=0) or if(n=1) then a value 1 is returned else fib function is called
recursively. This recursive process is repeated till the required Fibonacci series is
obtained.
SCHEMES
Scheme interpreters are readily available (and free) for a wide variety of computers.
The Scheme language, which is a dialect of LISP, was developed at MIT in the mid-
1970s. It is characterized by its small size, its exclusive use of static scoping, and its
treatment of functions as first-class entities.
There are a large number of other numeric functions in Scheme, among them
MODULO, ROUND, MAX, MIN, LOG, SIN, and SQRT. SQRT returns the square
root of its numeric parameter, if the parameter’s value is not negative. If the parameter
is negative, SQRT yields a complex number.
Defining Functions
A Scheme program is a collection of function definitions.
In Scheme, a nameless function actually includes the word LAMBDA, and is called
a lambda expression. For example,
(LAMBDA (x) (* x x))
Output Functions
Scheme includes a few simple output functions, but when used with the interactive
interpreter, most output from Scheme programs is the normal output from the
interpreter, displaying the results of applying EVAL to top-level functions.
Scheme includes a formatted output function, PRINTF, which is similar to the printf
function of C.
The Scheme two-way selector function, named IF, has three parameters: a predicate
expression, a then expression, and an else expression. A call to IF has the form
A function is tail recursive if its recursive call is the last operation in the function.
This means that the return value of the recursive call is the return value of the
nonrecursive call to the function.
ML(META LANGUAGE):
The value declaration statements are used to bind the names to values.
Syntax
Val identifier= expression;
Ml Supports arithmetic, Boolean, string , Selection control flow and list expressions.
Syntax
fun function_name(formal_paramters)=expression.
1. LISP is versatile and powerful language that is used in list processing and
symbolic computation
2. LISP Includes Knowledge Representation, Machine Learning, Natural
Language Processing, Intelligent Training Systems, Modelling of Speech and
Vision.
3. LISP is also used in writing the systems software for the LISP machine
4. It is oftenly used in the construction of various experimental systems
5. Scheme another FPL is used to teach preliminary programming courses in
some universities
6. Use of ML are confined to research laboratories and universities.
The language that are directly based on the Von-Neumann architecture are called
imperative languages.
FPL IPL
1. In these languages the programmers These languages are directly based on
need not be concerned with the variables the Von –Neumann architecture , hence
because the memory cell are not the programmers must manage the
abstracted into the language variables and assign the values to them.
2. Efficiency is Less 2. Efficiency is more
3. Less Labor is required for constructing 3. Increased Labor is required for
the programs constructing the programs
4. These Languages have simple syntactic 4. These Languages have complex
structures syntactic structures
5. Their semantics are simpler than the 5. They have complex semantics
imperative languages
6. Concurrent execution is easy as the 6. Concurrent execution is difficult to
programs are first translating into graphs design and use
which in turn can be executed through
graph reduction methods
7.Programmer is not concerned with the 7. Cooperation among the multiple
cooperation synchronization concurrent tasks is the responsibility of
the programmer
8. Execution of concurrent programs is 8. Concurrent programs execution is
easily understand difficult to understand
9.The program is dynamically divided 9.The program is statically divided into
into concurrent parts by the programmer concurrent parts by the programmer.
A proposition can be thought of as a logical statement that may or may not be true. It
consists of objects and the relationships among objects. Formal logic was developed
to provide a method for describing propositions, with the goal of allowing those
formally stated propositions to be checked for validity. Symbolic logic can be used
for the three basic needs of formal logic: to express propositions, to express the
relationships between propositions, and to describe how new propositions can be
inferred from other propositions that are assumed to be true. There is a close
relationship between formal logic and mathematics. In fact, much of mathematics can
be thought of in terms of logic. The fundamental axioms of number and set theory are
the initial set of propositions, which are assumed to be true. Theorems are the
additional propositions that can be inferred from the initial set. The particular form of
symbolic logic that is used for logic programming is called first-order predicate
calculus.
PREDICATE CALCULUS
Propositions
Clausal Form:
Problem with predicate calculus is that there are too many different ways of stating
propositions that have the same meaning; that is, there is a great deal of redundancy.
This is not such a problem for logicians, but if predicate calculus is to be used in an
automated (computerized) system, it is a serious problem. To simplify matters, a
standard form for propositions is desirable. Clausal form, which is a relatively simple
form of propositions, is one such standard form. All propositions can be expressed in
clausal form.
Terms:
A Prolog term is a constant, a variable, or a structure. A constant is either an atom
or an integer. Atoms are the symbolic values of Prolog and are similar to their
counterparts in LISP. In particular, an atom is either a string of letters, digits, and
The functor is any atom and is used to identify the structure. The parameter list can be
any list of atoms, variables, or other structures.
Fact Statements
Prolog statements begins with those statements used to construct the hypotheses, or
database of assumed information—the statements from which new information can be
inferred.
Prolog has two basic statement forms; these correspond to the headless and headed
Horn clauses of predicate calculus. The simplest form of headless Horn clause in
Prolog is a single structure, which is interpreted as an unconditional assertion, or fact.
Logically, facts are simply propositions that are assumed to be true. Prolog statement
is terminated by a period.
Rule Statements
The other basic form of Prolog statement for constructing the database corresponds
to a headed Horn clause.
Conjunctions contain multiple terms that are separated by logical AND operations. In
Prolog, the AND operation is implied. The structures that specify atomic propositions
in a conjunction are separated by commas, so one could consider the commas to be
AND operators.
Goal Statements
The theorem is in the form of a proposition that we want the system to either prove or
disprove. In Prolog, these propositions are called goals, or queries.
Simple Arithmetic
Prolog supports integer variables and integer arithmetic. Originally, the arithmetic
operators were functors, so that the sum of 7 and the variable X was formed with
+ (7, X)
Prolog now allows a more abbreviated syntax for arithmetic with the is operator. This
operator takes an arithmetic expression as its right operand and a variable as its left
operand. All variables in the expression must already be instantiated, but the left-side
variable cannot be previously instantiated. For example, in
A is B / 17 + C.
Prolog does not have assignment statements in the same sense as imperative
languages. They are simply not needed in most of the programming for which Prolog
was designed.
Prolog has a built-in structure named trace that displays the instantiations of values to
variables at each step during the attempt to satisfy a given goal. trace is used to
understand and debug Prolog programs.
List Structures
Atomic propositions, which are also called structures, are actually a form of records.
The other basic data structure supported is the list. Lists are sequences of any number
of elements, where the elements can be atoms, atomic propositions, or any other
terms, including other lists. Prolog uses the syntax of ML and Haskell to specify lists.
The list elements are separated by commas, and the entire list is delimited by square
brackets.
DEFICIENCIES OF PROLOG
Prolog, for reasons of efficiency, allows the user to control the ordering of pattern
matching during resolution. In a pure logic programming environment, the order of
attempted matches that take place during resolution is nondeterministic, and all
matches could be attempted concurrently.
Intrinsic Limitations
A fundamental goal of logic programming, is to provide nonprocedural programming;
that is, a system by which programmers specify what a program is supposed to do but
need not specify how that is to be accomplished.
These are the systems which stores data in tabular form. Relational Calculus is used
to perform queries on such databases. Tables containing the information can be
described by Prolog structures and the relationships between the tables can be
explained by Prolog rules.
Advantages:
1. Only single language is required for implementing RDBMS. All the queries
related to data definitions, data manipulations and input and output functions
can be done by using a single logic programming language.
2. Deductive capability is built in the logic programming languages, which is
useful for implementing RDBMS. Deducing data from conventional RDBMS
is not possible as it only contains facts but not inference rules.
Disadvantage:
Use of logic programming for implementing RDBMS is a slow process
Expert Systems
Expert systems are computer systems that have been developed for imitating human
expertise in same domain.
Natural-Language Processing
Logic programming is used in natural language processing in providing interfaces to
computer software systems such as intelligent databases and knowledge based
systems.
Education
Logic programming such as micro prolog can be used in the field of education which
provides the advantage as it introduces computing.
MULTIPARADIGM LANGUAGES
Ex: C#, which includes imperative and object-oriented paradigms as well as some
support for functional programming with features like delegates (allowing functions
to be treated as first-order objects), type inference, anonymous
functions and Language Integrated Query. Other examples are F# and Scala, which
provides similar functionality to C# but also includes full support for functional
programming (including currying, pattern matching, algebraic data types, lazy
evaluation, tail recursion, immutability, etc.). Perhaps the most extreme example
is Oz, which has subsets that adhere to logic (Oz descends from logic
programming), functional, object-oriented, dataflow concurrent, and other paradigms.
Oz was designed over a ten-year period to combine in a harmonious way concepts
that are traditionally associated with different programming paradigms. Lisp, while
often taught as a functional language, is known for its malleability and thus its ability
to engulf many paradigms.
Ex: Supporting this view, JavaScript supports, or infact uses various styles. For
example, its syntax follows a C language like structure, which is a procedural
language, and at the same time JavaScript copies many names and naming
conventions from an object-oriented programming language, Java, but the two
languages are otherwise unrelated and have very different semantics. The key design
principles within JavaScript are taken from the Self and Scheme programming
languages.
Ex: