0% found this document useful (0 votes)
42 views

PPL Imp

The document discusses reasons for studying programming language concepts, how to evaluate languages, and influences on language design. It provides several key benefits of studying programming language concepts, including increased ability to express ideas, improved background for choosing appropriate languages, ability to learn new languages more easily, and ability to design new languages. When evaluating languages, quantitative assessments focus on comprehension while qualitative assessments better reflect actual language use for communication. New technologies now enable more robust qualitative evaluations. Major influences on language design include purpose, programming paradigms, syntax/semantics, abstraction/modularity, memory management, concurrency, safety, performance, community, legacy compatibility, tooling, and technological advances. Educational goals and evolution of

Uploaded by

immuimran9398
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views

PPL Imp

The document discusses reasons for studying programming language concepts, how to evaluate languages, and influences on language design. It provides several key benefits of studying programming language concepts, including increased ability to express ideas, improved background for choosing appropriate languages, ability to learn new languages more easily, and ability to design new languages. When evaluating languages, quantitative assessments focus on comprehension while qualitative assessments better reflect actual language use for communication. New technologies now enable more robust qualitative evaluations. Major influences on language design include purpose, programming paradigms, syntax/semantics, abstraction/modularity, memory management, concurrency, safety, performance, community, legacy compatibility, tooling, and technological advances. Educational goals and evolution of

Uploaded by

immuimran9398
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 75

UNIT-I

ANSWERS
Q1)What are the reasons for studying the concepts of Programming
Languages?

The programming language design and implementation is often regarded as largely or even
completely, a matter of opinion, with few, if any, organizing principles, and no generally
accepted facts. In research laboratories and industries dozens of languages are uses every day,
each with its adherents and detractors. Some would suggest that all programming languages
are equivalent, the only difference being a matter of personal interest. Yet can we really say
that the computer programming language Java is “better” (or “worse”) than C++? Is Scheme
“better” than Lisp? Is Machine level language “better” than either of them? It is still a question
that which programming language is better and why? So the study of principle of programming
language supports to better understand the basic logics of programming languages and its
adherents and detractors. It’s also supports to understand the programming languages
paradigms. The following is what we believe to be a compelling list of potential benefits of
studying principle of programming languages:

 Increased ability to express ideas:


o It is widely believed that the depth at which a programmer think is influenced
by the expressive power of the language in which programmer communicate
our thoughts. It is difficult for people to conceptualize structures they can’t
describe, verbally or in writing.
o Language in which a programmer develops software places limits on the kinds
of control structures, data structures, and abstractions they can use.
o Awareness of a wider variety of programming language features can reduce
such limitations in software development.
o Can language constructs be simulated in other languages that do not support
those constructs directly?

 Improved background for choosing appropriate languages:


o Many programmers, when given a choice of languages for a new project,
continue to use the language with which they are most familiar, even if it is
poorly suited to new projects.
o If these programmers were familiar with other languages available, they would
be in a better position to make informed language choices.

 Provides greater ability to learn new languages:


o Programming languages are still in a state of continuous evolution, which means
continuous learning is essential.
o Programmers who understand the concept of OO programming will have easier
time learning Java.
o Once a thorough understanding of the fundamental concepts of languages is
acquired, it becomes easier to see how concepts are incorporated into the design
of the language being learned.

 Understand significance of implementation:


o Understanding of implementation issues leads to an understanding of why
languages are designed the way they are.
o This in turn leads to the ability to use a language more intelligently, as it was
designed to be used.

 Ability to design new languages:


o The more languages you gain knowledge of, the better understanding of
programming languages concepts you understand.

 Overall advancement of computing:


o In some cases, a language became widely used, at least in part, b/c those in
positions to choose languages were not sufficiently familiar with P/L concepts.
o 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.

Q2) How can evaluate the language explain it?


Quantitative or statistical assessment

Historically, this has been the most popular way to evaluate language tests due to it’s
practical advantages: it’s often cheaper and easier to organise.

On the other hand, this method only enables evaluation of a candidates comprehension.
Moreover, it tends to validate knowledge rather than ability. While it may be useful in a
training context, for example to validate the achievements of a specific course, it will only
give a partial view of a candidate's ability to use a language to communicate and express
themselves.

Qualitative assessment

Qualitative evaluation, enables evaluation in situations which better reflect the actual use of a
language, for example to communicate and express oneself, both orally and in writing.

However, for practical reasons this is not the most commonly used way of assessing
candidates. Historically this method would involve candidates taking a listening, reading and
writing test and then also attending an interview with a teacher to assess their oral skills -
expensive and can be very complex to organise, especially when you need to evaluate a large
number of candidates quickly.

Secondly, the method used to complete qualitative evaluation needs to be very rigorous to
ensure objectivity and reliability. Interviews must be conducted in a structured manner,
assessment criteria defined precisely, and examiners must be trained and their judgment
regularly monitored.
The future of language assessment

The rise of new technology has opened the door to new ways of capturing data. It’s possible
to record oral samples and written responses from any computer with a microphone, or even
from a smartphone. Additionally, it’s far easier to present candidates with real-life situations
through the use of visuals and recordings.

Further, the anonymisation of candidates and Big Data technology makes it possible to set up
even more robust methods to guarantee the objectivity and reliability of evaluation.
Technology also enables the use of the skills of global examiners.

Q3) What are the major influences on language design?

The design of programming languages is influenced by a variety of factors, and these


influences can vary based on the goals, philosophies, and requirements of the language
designers. Here are some major influences on language design:

1. Purpose and Domain:


o General-Purpose vs. Domain-Specific: The intended use of the language,
whether it's for general-purpose programming or targeted at specific domains
(e.g., web development, scientific computing), significantly influences its
design.
2. Programming Paradigms:
o Imperative, Functional, Object-Oriented, Logic: The choice of
programming paradigms can heavily influence language design. Some
languages support multiple paradigms, offering developers flexibility.
3. Syntax and Semantics:
o Readability and Expressiveness: Languages often aim to be readable and
expressive, enabling developers to write clear and concise code. This
influences choices in syntax and semantics.
4. Abstraction and Modularity:
o Levels of Abstraction: Languages may support different levels of abstraction,
from low-level details to high-level abstractions, influencing how developers
interact with the underlying system.
5. Memory Management:
o Manual vs. Automatic Memory Management: The choice of how memory
is managed—either manually by the programmer or automatically by the
language runtime—affects the language's simplicity, performance, and safety.
6. Concurrency and Parallelism:
o Support for Concurrency: As multi-core processors become more prevalent,
languages may incorporate features to facilitate concurrent and parallel
programming.
7. Safety and Security:
o Type Systems and Memory Safety: Languages may incorporate strong type
systems, memory safety features, and other mechanisms to enhance program
correctness and security.
8. Performance:
o Compiled vs. Interpreted: The performance goals of a language can
influence whether it is compiled to machine code or interpreted at runtime.
9. Community and Ecosystem:
o Developer Community: The existing developer community and ecosystem
around a language can impact its evolution and adoption.
10. Legacy and Compatibility:
o Compatibility with Existing Code: Considerations of backward
compatibility and support for existing codebases can influence language
design decisions.
11. Tooling and Libraries:
o Availability of Tools and Libraries: The availability of development tools,
frameworks, and libraries can greatly impact a language's usability and
productivity.
12. Evolution of Technology:
o Technological Advances: Advances in hardware, networking, and other
technologies may prompt the inclusion of new features or optimizations in
programming languages.
13. Educational Goals:
o Teaching and Learning: Some languages are designed with educational
purposes in mind, aiming to introduce programming concepts in a clear and
understandable way.

Q4) Distinguish between procedure-oriented function oriented, rule based


and object-oriented languages.
Q5) Explain the three methods of implementing a PL?
1. Compilation: It takes the input in a particular language, translates it into another one which may
now be the input for another compiler. Thus, a compiler does not directly implement the instructions it
receives.
2. Pure Interpretation: It takes the input in a particular language, uses it in the same language and
performs the instructions given on a machine.
3. Hybrid Implementation: This is an in-between of compilers and pure interpreters. This allows both
the decoding of high level language into easy ones and the basic options of interpreting these.

Q6) What are the syntactic structures or element that can be described
unity BNF notation?

In Backus-Naur Form (BNF), a notation used to formally describe the syntax of programming
languages and other formal languages, several syntactic structures or elements are commonly
used. BNF is composed of rules that define how sentences in a language can be constructed.
Here are the fundamental elements found in BNF notation:

1. Non-Terminals:
o Definition: Non-terminals represent syntactic categories or placeholders for
other syntactic structures.
o Format: Non-terminals are usually written in uppercase letters (e.g.,
<Statement> or <Expression>).
2. Terminals:
o Definition: Terminals represent actual symbols or tokens in the language,
such as keywords, operators, or literals.
o Format: Terminals are typically written in lowercase letters or enclosed in
quotation marks (e.g., if or "+").
3. Production Rules:
o Definition: Production rules define how non-terminals can be expanded into
sequences of terminals and/or other non-terminals.
o Format: Production rules are written in the form of <NonTerminal> ::= <Sequence
of Symbols>.
4. Alternatives (Choice):
o Definition: Alternatives indicate that a given non-terminal can be expanded in
multiple ways.
o Format: Alternatives are separated by the vertical bar ( |) symbol (e.g., <Expr>
::= <Term> | <Expr> "+" <Term>).
5. Optional Elements:
o Definition: Optional elements indicate that a certain part of the syntax may or
may not be present.
o Format: Enclosed in square brackets ([]) (e.g., <Statement> ::= "if" <Condition> [
"then" <Statement> ]).
6. Repetition (Zero or More):
o Definition: Repetition allows a certain element to be repeated zero or more
times.
o Format: Enclosed in curly braces ({}) or specified using an asterisk (*) (e.g.,
<List> ::= <Item> { "," <Item> }).
7. Grouping:
o Definition: Grouping is used to specify a sequence of elements that should be
treated as a single unit.
o Format: Enclosed in parentheses (()) (e.g., <Expression> ::= "(" <Term> ")").
8. Comments:
o Definition: Comments are used to provide explanatory notes within the BNF
notation.
o Format: Comments are often denoted by specific symbols or annotations,
depending on the BNF variant.

Q7) Give BNF notation for identifiers, for loop while loop, while loop in C.
Give the syntax graph.

with a simple syntax graph for better visualization.

BNF Notation for Identifiers:


<Identifier> ::= <Letter> { <Letter> | <Digit> | "_" }
<Letter> ::= "A" | "B" | ... | "Z" | "a" | "b" | ... | "z"
<Digit> ::= "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"

BNF Notation for For Loop in C:


<ForLoop> ::= "for" "(" <Expression_opt> ";" <Expression_opt> ";" <Expression_opt> ")" <Statement>
<Expression_opt> ::= <Expression> | ε

BNF Notation for While Loop in C:

<WhileLoop> ::= "while" "(" <Expression> ")" <Statement>

Syntax Graph for a Simple While Loop in C:

Here's a simplified syntax graph for a while loop in C:

+---------------------+
| while (<expr>) |
| | |
| V |
| +-----------------+ |
| | <statement> | |
| +-----------------+ |
+---------------------+

Q8)Explain parse trees with an example.

 Parse : It means to resolve (a sentence) into its component parts and describe their
syntactic roles or simply it is an act of parsing a string or a text.
 Tree: A tree may be a widely used abstract data type that simulates a hierarchical tree
structure, with a root value and sub-trees of youngsters with a parent node,
represented as a group of linked nodes.

Parse Tree:

 Parse tree is the hierarchical representation of terminals or non-terminals.


 These symbols (terminals or non-terminals) represent the derivation of the grammar
to yield input strings.
 In parsing, the string springs using the beginning symbol.
 The starting symbol of the grammar must be used as the root of the Parse Tree.
 Leaves of parse tree represent terminals.
 Each interior node represents productions of a grammar.

Rules to Draw a Parse Tree:

1. All leaf nodes need to be terminals.


2. All interior nodes need to be non-terminals.
3. In-order traversal gives the original input string.

Example 1: Let us take an example of Grammar (Production Rules).

S -> sAB
A -> a
B -> b
The input string is “sab”, then the Parse Tree is:

Example-2: Let us take another example of Grammar (Production Rules).

S -> AB
A -> c/aA
B -> d/bB

The input string is “acbd”, then the Parse Tree is as follows:

Uses of Parse Tree:

 It helps in making syntax analysis by reflecting the syntax of the input language.
 It uses an in-memory representation of the input with a structure that conforms to the
grammar.
 The advantages of using parse trees rather than semantic actions: you’ll make multiple
passes over the info without having to re-parse the input.

Q9)Example in detail about attribute grammar?

Attribute grammars are a formalism for specifying the semantics of programming languages.
They extend context-free grammars by associating attributes with the grammar symbols and
defining rules for computing attribute values. Attribute grammars play a crucial role in formal
language definition, compiler construction, and program analysis.

The notation used to describe attribute grammars is often similar to Backus-Naur Form
(BNF). In the context of attribute grammars, the symbols are annotated with attributes, and
semantic rules are associated with the production rules of the grammar.

Q10)What are the difference between synthesis and inherited attributes?


Q11)Differentiate between operational, axiomatic and denotational
semantics.

Operational semantics:

This says that the meaning of a language construct is specified by the computation it induces.
It is of interest how the effect of a computation is produced. My understanding of this is that
this basically describes the meaning of all the operations involved in a program (from the
most basic to the most complex).

Examples:

arithmetic operations: 1 + 1, 10 ** 2, 19 // 3 etc. In this case it analyzes the meaning of the


steps involved in producing a result given n operands and n operators. This can be further
boiled down to what each operand means (so in my examples each number is defined in the
domain of natural numbers [1, 2, ..., n], etc.

assignment operations: x = 5, y = 5 ** 2, z = 10 ** 2 // 3 * (99 + 1024) etc. In this case it involves


an evaluation of the value of the mathematical expression on the right and assigning it to the
identifier on the left.

augmented assignment operations: x += y, z *= t etc. In this case it involves an evaluation of


each identifier once, and performing an arithmetic operation first, followed by an assignment
operation last.

etc.

Denotational semantics:
This says that meanins are modelled by mathematical objects that represent the effect of
executing the constructs. It is of interest only the effect of a computation, not how it is
produced. My understanding of this is basically mathematical functions, which take
something as an input, do some computation (which you don't care about) and produce a
result, which you care about. Since denotational means the main meaning, I take this as: the
name of your function should constrain the possible interpretations of what it does, ideally to
be exact.

Examples:

sort(iterable): should pretty much do what it says, take an unordered iterable as its input and
return it ordered.

min(iterable): should take an array return the smallest value (you don't care how it does it)

max(iterable): should take an array return the largest value (you don't care how it does it)

abs(x): return the absolute value of a number

etc.

Axiomatic semantics:

Some properties of the effect of executing the constructs are expressed as assertions. Some
aspects of the executions may be ignored. My understanding of this is that it's related to
boolean algebra and logic.

Examples:

expr1 and expr2: if expr1 is False then the entire boolean expression is False and it short-
circuits and expr2 is not evaluated

Or even compound statements:

if expr1:
elif expr2:
elif expr3:
else:

The effect is the result of executing the above construct and you assert its value based on
whichever boolean expression yield true, the rest of them being ignored.
UNIT - II
Q1)What are the design issues for names? Explain it?
– Maximum length?
– Are connector characters allowed?
– Are names case sensitive?
– Are special words reserved words or keywords?
Length
– If too short, they cannot be connotative
– Language examples:
o FORTRAN I: maximum 6
o COBOL: maximum 30
o FORTRAN 90 and ANSI C: maximum 31
o Ada and Java: no limit, and all are significant
o C++: no limit, but implementors often impose one
Connectors
– Pascal, Modula-2, and FORTRAN 77 don't allow
– Others do
Case sensitivity
– Disadvantage: readability (names that look alike are different)
o worse in C++ and Java because predefined names are mixed case (e.g.,
IndexOutOfBoundsException)
– C, C++, and Java names are case sensitive
– The names in other languages are not
Special words
– An aid to readability; used to delimit or separate statement clauses
– Def: A keyword is a word that is special only in certain contexts
o i.e. in Fortran:
– Real VarName (Real is data type followed with a name, therefore Real is
a keyword)
– Real = 3.4 (Real is a variable)
– Disadvantage: poor readability
– Def: A reserved word is a special word that cannot be used as a user-defined
name

Q2)Explain in detail about binding and its types.


The Concept of Binding
The l-value of a variable is its address
The r-value of a variable is its value
Def: A binding is an association, such as between an attribute and an entity, or
between an operation and a symbol
Def: Binding time is the time at which a binding takes place.
Possible binding times:
– Language design time--e.g., bind operator symbols to operations
– Language implementation time--e.g., bind floating point type to a
representation
– Compile time--e.g., bind a variable to a type in C or Java
– Load time--e.g., bind a FORTRAN 77 variable to a memory cell (or a C static
variable)
– Runtime--e.g., bind a nonstatic local variable to a memory cell
Def: A binding is static if it first occurs before run time and remains unchanged
throughout program execution.
Def: A binding is dynamic if it first occurs during execution or can change
during execution of the program.
Type Bindings
– How is a type specified?
– When does the binding take place?
– If static, the type may be specified by either an explicit or an implicit
declaration
Def: An explicit declaration is a program statement used for declaring the types
of variables
Def: An implicit declaration is a default mechanism for specifying types of
variables (the first appearance of the variable in the program)
FORTRAN, PL/I, BASIC, and Perl provide implicit declarations
– Advantage: writability
– Disadvantage: reliability (less trouble with Perl)
Dynamic Type Binding (JavaScript and PHP)
Specified through an assignment statement e.g., JavaScript
list = [2, 4.33, 6, 8];
list = 17.3;
– Advantage: flexibility (generic program units)
– Disadvantages:
o High cost (dynamic type checking and interpretation)
o Type error detection by the compiler is difficult
Type Inferencing (ML, Miranda, and Haskell)
– Rather than by assignment statement, types are determined from the context
of the reference
Storage Bindings & Lifetime
– Allocation - getting a cell from some pool of available cells
– Deallocation - putting a cell back into the pool
29
Def: The lifetime of a variable is the time during which it is bound to a
particular memory cell
Categories of variables by lifetimes
– Static--bound to memory cells before execution begins and remains bound to
the same memory cell throughout execution.
e.g., all FORTRAN 77 variables, C static variables
– Advantages: efficiency (direct addressing), history-sensitive subprogram
support
– Disadvantage: lack of flexibility (no recursion)
Categories of variables by lifetimes
– Stack-dynamic--Storage bindings are created for variables when their
declaration statements are elaborated.
– If scalar, all attributes except address are statically bound
e.g., local variables in C subprograms and Java methods
– Advantage: allows recursion; conserves storage
– Disadvantages:
o Overhead of allocation and deallocation
o Subprograms cannot be history sensitive
o Inefficient references (indirect addressing)
Categories of variables by lifetimes
– Explicit heap-dynamic--Allocated and deallocated by explicit directives,
specified by the programmer, which take effect during execution
– Referenced only through pointers or references
e.g., dynamic objects in C++ (via new and delete) all objects in Java
– Advantage: provides for dynamic storage management
– Disadvantage: inefficient and unreliable
Categories of variables by lifetimes
– Implicit heap dynamic--Allocation and deallocation caused by assignment
statements
e.g., all variables in APL; all strings and arrays in Perl and JavaScript
– Advantage: flexibility
– Disadvantages:
o Inefficient, because all attributes are dynamic
o Loss of error detection

Q3)Discuss about type checking.


Type Checking - CO3
Generalize the concept of operands and operators to include subprograms and
assignments
Type checking is the activity of ensuring that the operands of an operator are of
compatible types
A compatible type is one that is either legal for the operator, or is allowed under
language rules to be implicitly converted, by compiler- generated code, to a legal
type. This automatic conversion is called as coercion.
A type error is the application of an operator to an operand of an inappropriate
type
If all type bindings are static, nearly all type checking can be static
If type bindings are dynamic, type checking must be dynamic
Def: A programming language is strongly typed if type errors are always detected

Q4)Define type coercion and also discuss the type.

Type Coercion:

Type coercion, also known as type conversion, is the process of converting a value from one
data type to another. It involves changing the type of a data element, typically to make it
compatible with the operations or expectations of a particular operation or context. Type
coercion can be implicit, where the conversion is automatically done by the programming
language, or explicit, where the programmer explicitly specifies the conversion.

Implicit Type Coercion: Implicit type coercion happens automatically by the programming
language without the need for explicit instructions from the programmer. It often occurs in
situations where values of one type are used in a context that expects a different type. The
language automatically performs the necessary conversion.

Example (in JavaScript):

javascript
var num = 5; // num is implicitly of type number
var str = "Hello"; // str is implicitly of type string

var result = num + str; // JavaScript will implicitly convert num to a string and perform concatenation
console.log(result); // Output: "5Hello"

In this example, the addition operation involves a number and a string. JavaScript implicitly
converts the number to a string and concatenates them.

Explicit Type Coercion: Explicit type coercion is when the programmer explicitly specifies
the conversion from one type to another using casting or conversion functions provided by
the language.

Example (in Python):

python
num_str = "123"
num_int = int(num_str) # Explicitly converting a string to an integer using the int() function
print(num_int) # Output: 123

Here, the int() function is used to explicitly convert a string to an integer.

Type in Programming Languages:

In programming languages, types define the kind of data that a variable can hold and the
operations that can be performed on that data. Types can be broadly categorized into
primitive types and user-defined types.

1. Primitive Types:
o Numeric Types: Integers (e.g., int), floating-point numbers (e.g., float), etc.
o Text Type: String (e.g., str).
o Boolean Type: Boolean values (True or False).
2. User-Defined Types:
o Classes and Objects: In object-oriented programming, developers can define
their own types using classes.
3. Composite Types:
o Arrays, Lists, Tuples: Collections of elements with a specific structure.
4. Special Types:
o Null/Undefined: A special type representing the absence of a value.
o Function Types: In languages that support first-class functions, functions can
be treated as types.

Understanding and managing types is crucial for writing correct and efficient programs. Type
coercion, whether implicit or explicit, helps handle situations where values of different types
need to interact. However, developers should be aware of potential issues and unintended
consequences that may arise from automatic type coercion.

Q5)Explain in detail about named constants.


Named Constants
Def: A named constant is a variable that is bound to a value only when it is
bound to storage
Advantages: readability and modifiability
Used to parameterize programs
The binding of values to named constants can be either static (called manifest
constants) or dynamic
Languages:
– Pascal: literals only
– FORTRAN 90: constant-valued expressions
– Ada, C++, and Java: expressions of any kind
Variable Initialization
Def: The binding of a variable to a value at the time it is bound to storage is
called initialization
Initialization is often done on the declaration statement e.g., Java int sum = 0

Q6)Explain about the design issues for named constants.

Named constants are identifiers associated with fixed values in a program, and they provide a
way to assign a meaningful name to a constant value. Designing named constants involves
making decisions about how to declare, use, and manage these constants in a programming
language. Here are some design issues related to named constants:

1. Syntax and Declaration:


o Issue: How are named constants declared in the programming language?
o Considerations: Consider using a keyword like const or final followed by
the constant's name and value. Should the type of the constant be explicitly
specified, or should it be inferred by the compiler?
2. Visibility and Scope:
o Issue: What is the scope and visibility of named constants?
o Considerations: Decide whether named constants should have global scope,
be limited to a specific module or class, or follow other scoping rules.
Consider the potential impact on code readability and maintenance.
3. Namespace and Naming Conventions:
o Issue: How should named constants be named to avoid conflicts and enhance
readability?
o Considerations: Define naming conventions for constants to ensure clarity
and prevent naming collisions. Consider using a prefix or a specific naming
style (e.g., MAX_SIZE, PI_VALUE).
4. Initialization and Immutability:
o Issue: Should named constants be initialized at the time of declaration, and
should they be immutable?
o Considerations: Decide whether constants must be initialized when declared,
and if they should be immutable (i.e., their values cannot be changed after
initialization). Immutability can enhance predictability and maintainability.
5. Type Constraints:
o Issue: Should there be constraints on the types of values assigned to named
constants?
o Considerations: Determine whether there should be restrictions on the types
of values that can be assigned to constants. This can help catch errors at
compile-time and improve code safety.
6. Compile-Time vs. Runtime Evaluation:
o Issue: Should the value of named constants be determined at compile-time or
runtime?
o Considerations: Consider the performance implications and decide whether
the value of constants should be known at compile-time or if it's acceptable for
them to be computed at runtime.
7. Integration with Enums or Enumerated Types:
o Issue: Should named constants be integrated with enumerated types?
o Considerations: In languages that support enums, consider whether named
constants should be part of an enum or whether they should exist
independently.
8. Documentation:
o Issue: How should documentation for named constants be managed?
o Considerations: Ensure that named constants are well-documented, including
information about their purpose, allowed values, and any relevant constraints.
This can enhance code maintainability and help other developers understand
the constants.
9. Use of Constants in Expressions:
o Issue: Can named constants be used in expressions, and if so, how?
o Considerations: Decide whether constants can participate in mathematical or
logical expressions, and if there are any restrictions on their use in such
contexts.
10. Integration with Configuration Management:
o Issue: How are constants managed in configuration files or external
configurations?
o Considerations: If constants are used for configuration parameters, consider
how they can be managed in configuration files, external databases, or other
configuration management systems.

Q7)What is user defined data type?


User-Defined Ordinal Types - CO2
An ordinal type is one in which the range of possible values can be easily
associated with the set of positive integers
Examples of primitive ordinal types in Java
– integer
– char
– boolean
Enumeration Types
All possible values, which are named constants, are provided in the definition
C# example
enum days {mon, tue, wed, thu, fri, sat, sun};
Design issues
– Is an enumeration constant allowed to appear in more than one type
definition, and if so, how is the type of an occurrence of that constant
checked?
– Are enumeration values coerced to integer?
– Any other type coerced to an enumeration type?
Evaluation of Enumerated Type
Aid to readability, e.g., no need to code a color as a number
Aid to reliability, e.g., compiler can check:
– Operations (don‘t allow colors to be added)
– No enumeration variable can be assigned a value outside its defined range
– Ada, C#, and Java 5.0 provide better support for enumeration than C++
because enumeration type variables in these languages are not coerced into
integer types
Subrange Types
An ordered contiguous subsequence of an ordinal type
– Example: 12..18 is a subrange of integer type
Ada‘s design
type Days is (mon, tue, wed, thu, fri, sat, sun);
subtype Weekdays is Days range mon..fri;
subtype Index is Integer range 1..100;
Day1: Days;
Day2: Weekday;
Day2 := Day1;
Subrange Evaluation
Aid to readability
– Make it clear to the readers that variables of subrange can store only certain
range of values
Reliability
– Assigning a value to a subrange variable that is outside the specified range is
detected as an error
Implementation
Enumeration types are implemented as integers
Subrange types are implemented like the parent types with code inserted (by
the
compiler) to restrict assignments to subrange variables
20
Array Types
An array is an aggregate of homogeneous data elements in which an individual
element is identified by its position in the aggregate, relative to the first element.
Array Design Issues
What types are legal for subscripts?
Are subscripting expressions in element references range checked?
When are subscript ranges bound?
When does allocation take place?
What is the maximum number of subscripts?
Can array objects be initialized?
Are any kind of slices supported?
Array Indexing
Indexing (or subscripting) is a mapping from indices to elements
array_name (index_value_list)an element
Index Syntax
– FORTRAN, PL/I, Ada use parentheses
Ada explicitly uses parentheses to show uniformity between array references
and function calls because both are mappings
– Most other languages use brackets
Arrays Index (Subscript) Types
FORTRAN, C: integer only
Ada: integer or enumeration (includes Boolean and char)
Java: integer types only
Index range checking
– C, C++, Perl, and Fortran do not specify range checking
– Java, ML, C# specify range checking
– In Ada, the default is to require range checking, but it can be turned off

Q8) Explain the associative arrays.


Associative Arrays
An associative array is an unordered collection of data elements that are
indexed by an equal number of values called keys
– User-defined keys must be stored
Design issues:
– What is the form of references to elements?
– Is the size static or dynamic?
Associative Arrays in Perl
Names begin with %; literals are delimited by parentheses
%hi_temps = ("Mon" => 77, "Tue" => 79, ―Wed‖ => 65, …);
Subscripting is done using braces and keys
$hi_temps{"Wed"} = 83;
Elements can be removed with delete
delete $hi_temps{"Tue"};

Q9)Define arithmetic expression. Explain it..


Arithmetic Expressions – CO2, CO3
Arithmetic Expressions consist of operators, operands, parentheses and
function calls.
Design Issues
Design issues for arithmetic expressions
Operator precedence rules?
Operator associativity rules?
Order of operand evaluation?
Operand evaluation side effects?
Operator overloading?
Type mixing in expressions?
Operators
A unary operator has one operand.
A binary operator has two operands.
A ternary operator has three operands.
Operator Precedence Rules
The operator precedence rules for expression evaluation define the order in
which adjacent operators of different precedence levels are evaluated.
Typical precedence levels:
parentheses
unary operators
** (if the language supports it)
*, /
+, -
Operator Associativity Rule
The operator associativity rules for expression evaluation define the order in
which adjacent operators with the same precedence level are evaluated.
Typical associativity rules:
Left to right, except **(Ruby and Fortran), which is right to left
Sometimes unary operators associate right to left (e.g., in FORTRAN)
– APL is different; all operators have equal precedence and all operators
associate right to left.
– Precedence and associativity rules can be overridden with parentheses.
Conditional Expressions
33
Conditional Expressions (ternary operator ?:) available in C-based languages.
An example: (C, C++)
average = (count == 0)? 0 : sum/count
Evaluates as if written like
if (count == 0)
average = 0
else
average = sum /count
Operand Evaluation Order
Operand evaluation order as follows.
Variables: fetch the value from memory.
Constants: sometimes a fetch from memory; sometimes the constant is in the
machine language instruction.
Parenthesized expressions: evaluate all operands and operators first.
The most interesting case is when an operand is a function call.
Potentials for Side Effects Functional side effects: when a function changes a twoway
parameter or a non-local variable
Problem with functional side effects: When a function referenced in an
expression alters another operand of the expression;
e.g., for a parameter change:
a = 10;
/* assume that fun changes its parameter */
b = a + fun(a);
Two possible solutions to the functional side effects problem: Write the language
definition to disallow functional side effects.
No two-way parameters in functions
No non-local references in functions
Advantage: it works!
Disadvantages: inflexibility of one-way parameters and lack of non-local
references
– Write the language definition to demand that operand evaluation order be fixed.
Disadvantage: limits some compiler optimizations
– Java requires that operands appear to be evaluated in left-to-right order.

Q10) What is short-circuit evaluation? Discuss in detail.


Short Circuit Evaluation - CO3
An expression in which the result is determined without evaluating all of the
operands and/or operators
Example: (13*a) * (b/13–1)
If ‘a’ is zero, there is no need to evaluate (b/13-1)
35
Problem with non-short-circuit evaluation
index = 1;
while (index <= length) && (LIST[index] != value)
index++;
When index=length, LIST [index] will cause an indexing problem (assuming
LIST
has length -1 elements)
C, C++ and Java: use short-circuit evaluation for the usual Boolean operators
(&& and ||), but also provide bitwise Boolean operators that are not short
circuit (& and |)
Ada: programmer can specify either (short-circuit is specified with and then and
or else)
Short-circuit evaluation exposes the potential problem of side effects in
expressions e.g., (a > b) || (b++ / 3)

Q11) What is mixed mode assignment? Explain in detail.


Mixed Mode
A mixed-mode expression is one that has operands of different types
A coercion is an implicit type conversion
Disadvantage of coercions:
– They decrease in the type error detection ability of the compiler
In most languages, all numeric types are coerced in expressions, using widening
conversions.
In Ada, there are virtually no coercions in expressions
Explicit Type Conversions called as casting in C-based languages.
Examples:-
C: (int)angle, Ada: Float (Sum)
– Note that Ada’s syntax is similar to that of function calls
Errors in Expressions causes
Inherent limitations of arithmetic e.g., division by zero
Limitations of computer arithmetic e.g., overflow
Often ignored by the run-time system

Q12) Explain unconditional and guarded commands.


Unconditional Branching: User-Located Loop Control Mechanisms
Sometimes it is convenient for the programmers to decide a location for loop
control (other than top or bottom of the loop)
Simple design for single loops (e.g., break)
Design issues for nested loops
– Should the conditional be part of the exit?
– Should control be transferable out of more than one loop?
User-Located Loop Control Mechanisms break and continue
C , C++, Python, Ruby, and C# have unconditional unlabeled exits (break)
Java and Perl have unconditional labeled exits (break in Java, last in Perl)
C, C++, and Python have an unlabeled control statement, continue, that skips
the remainder of the current iteration, but does not exit the loop
Java and Perl have labeled versions of continue
Iterative Statements: Iteration Based on Data Structures
Number of elements of in a data structure control loop iteration
Control mechanism is a call to an iterator function that returns the next element
in some chosen order, if there is one; else loop is terminate
C's for can be used to build a user-defined iterator:
for (p=root; p==NULL;
traverse(p)){ }
C#‘s foreach statement iterates on the elements of arrays and other collections:
Strings[] = strList = {"Bob", "Carol", "Ted"};
foreach (Strings name in strList)
Console.WriteLine ("Name: {0}", name);
The notation {0} indicates the position in the string to be displayed
Perl has a built-in iterator for arrays and hashes, foreach Unconditional
Branching
Transfers execution control to a specified place in the program
Represented one of the most heated debates in 1960‘s and 1970‘s
Well-known mechanism: goto statement
Major concern: Readability
Some languages do not support goto statement (e.g., Java)
C# offers goto statement (can be used in switch statements)
Loop exit statements are restricted and somewhat camouflaged goto‘s
41
Guarded Commands
Designed by Dijkstra
Purpose: to support a new programming methodology that supported
verification (correctness) during development
Basis for two linguistic mechanisms for concurrent programming (in CSP and
Ada)
Basic Idea: if the order of evaluation is not important, the program should not
specify one
Selection Guarded Command
•Form
if <Boolean exp> -> <statement>
[] <Boolean exp> -> <statement>
...
[] <Boolean exp> -> <statement>
fi
Semantics: when construct is reached,
Evaluate all Boolean expressions
If more than one are true, choose one non-deterministically
If none are true, it is a runtime error
Loop Guarded Command
•Form
do <Boolean> -> <statement>
[] <Boolean> -> <statement>
...
[] <Boolean> -> <statement>
Od
Semantics: for each iteration
Evaluate all Boolean expressions
If more than one are true, choose one non-deterministically; then start loop
again
If none are true, exit loop
Guarded Commands: Rationale
Connection between control statements and program verification is intimate
Verification is impossible with goto statements
Verification is possible with only selection and logical pretest loops
Verification is relatively simple with only guarded commands
Summary
Expressions
Operator precedence and associativity
Operator overloading
Mixed-type expressions
Various forms of assignment
Variety of statement-level structures
Choice of control statements beyond selection and logical pretest loops is a
trade-off between language size and writability
Functional and logic programming languages are quite different control
structures

UNIT-III
Q1.Discuss about generic subprogram in Ada.

In Ada, a generic subprogram is a powerful feature that allows you to define a parameterized
subprogram, which can be instantiated with different types or values. This enables the
creation of flexible and reusable code that can work with a variety of data types and
structures. Ada provides both generic procedures and generic functions.

Here's an overview of generic subprograms in Ada:

Generic Procedures:

Syntax:
generic
procedure Procedure_Name (Generic_Parameters);
Example:
generic
type Element_Type is private;
procedure Swap (A, B: in out Element_Type);

In this example, Swap is a generic procedure that can be instantiated with different types
(Element_Type). The is private clause ensures that the actual type is hidden from the
users of the generic package.

Instantiation:
package Integer_Swap is new Swap (Element_Type => Integer);

Generic Functions:

Syntax:
generic
function Function_Name (Generic_Parameters) return Result_Type;
Example:

generic
type Element_Type is private;
function Max (A, B: Element_Type) return Element_Type;

In this example, Max is a generic function that can be instantiated with different types
(Element_Type). The is private clause ensures that the actual type is hidden from the
users of the generic package.

Instantiation:

package Integer_Max is new Max (Element_Type => Integer);

Generic Package:

You can also use generic packages to encapsulate a collection of related generic procedures
or functions.

Syntax:

generic
package Package_Name is
-- Specification of generic procedures or functions
end Package_Name;
Example:

generic
type Element_Type is private;
package Sorting is
procedure Sort (Array: in out Element_Type_Array);
end Sorting;

Instantiation:

package Integer_Sorting is new Sorting (Element_Type => Integer);

Benefits of Generic Subprograms in Ada:

1. Reusability: Generic subprograms allow you to write reusable code that can work
with various data types without duplicating the implementation.
2. Abstraction: The generic subprogram hides the details of the actual data types,
providing a level of abstraction that enhances code readability and maintainability.
3. Flexibility: Developers can instantiate generic subprograms with different types or
values based on the specific requirements of their applications.
4. Type Safety: The use of generics in Ada retains type safety, as the compiler ensures
that the instantiated types adhere to the rules specified in the generic definition.
5. Modularity: Generic subprograms promote modularity by separating the generic
algorithm or functionality from the specific data types it operates on.

In summary, Ada's support for generic subprograms enhances the language's flexibility,
reusability, and abstraction capabilities, making it a valuable feature for building robust and
adaptable software.

Q2.What are coroutines?


• The word “coroutine” is composed of two words: “co” (cooperative) and
“routines” (functions).
• Coroutines are functions that are cooperative.
• Coroutine is a special kind of subprogram.
• Coroutines have multiple entry points which are controlled by
themselves.

Q3.Discuss the design issues of subprogram.

Q4.Explain in detail about parameters.


PARAMETER PASSING METHODS
• Parameter-passing methods are the ways in which parameters are
transmitted to and/or from called subprograms.
• Parameter passing depends on model of subprogram.There are two
models for parameter passing-
1. Semantics Models of Parameter Passing
2. Implementation Models of Parameter Passing
1. Semantics Models of Parameter Passing:
• Formal parameters are characterized by one of three distinct semantics
models.
1. They can receive data from the corresponding actual parameter, called in
mode.
2. They can transmit data to the actual parameter, called out mode.
3. They can do both, called inout mode.
2. Implementation Models of Parameter Passing
• This model consist the following ways of parameter passing.
1. Pass by value
2. Pass by reference
3. Pass-by-Result
4. Pass-by-Value-Result
5. Pass-by-Name
1. Pass by value: Value of actual parameter in read only mode is transmitted
to formal parameters.
2. 1. Pass by value: Value of actual parameter in read only mode is
transmitted to formal parameters.
3. 2. Pass by reference: Reference/address of actual parameter is
transmitted to formal parameters.
4. 3. Pass-by-Result: When a parameter is passed by result, no value is
transmitted to the subprogram.
5. 4. Pass-by-Value-Result: Pass-by-value-result is an implementation
model for inout-mode parameters. Pass-by-value-result is sometimes
called pass-by-copy, because the actual
6. parameter is copied to the formal parameter at subprogram entry and then
7. copied back at subprogram termination.
8. 5. Pass-by-Name: Pass-by-name is an inout-mode parameter transmission
method. In it parameters are passed by name. Implementing a pass-by-
name parameter requires a subprogram to be passed to the called
subprogram to evaluate the address or value of the formal parameter.

Q5.Discuss about the semantic models of parameter passing


Semantics Models of Parameter Passing:
• Formal parameters are characterized by one of three distinct semantics
models.
1. They can receive data from the corresponding actual parameter, called in
mode.
2. They can transmit data to the actual parameter, called out mode.
3. They can do both, called inout mode.
Q6.Write about overloaded subprograms.
Overloaded Subprograms
• An overloaded subprogram is one that has the same name as another
subprogram in the same referencing environment.
• Every version of an overloaded subprogram has a unique protocol.
• C++, Java, C#, and Ada include predefined overloaded subprograms.
• In Ada, the return type of an overloaded function can be used to
disambiguate calls (thus two overloaded functions can have the same
parameters).
• Ada, Java, C++, and C# allow users to write multiple versions of
subprograms with the same name.
• Example: (C++)
• void fun( float b = 0.0 );
• void fun();
• …
• fun ( );

Q7.Describe abstract data types with suitable examples.

Abstract Data Types (ADTs) are a programming concept that encapsulates data structures and
the operations performed on them into a single unit. ADTs provide an abstraction by defining
a set of operations without specifying the internal details of how these operations are
implemented. This separation of concerns helps in organizing and structuring code,
enhancing modularity, and facilitating a clear distinction between the interface and the
implementation.

Here are some common examples of Abstract Data Types:

1. Stack:

 Description: A stack is a Last-In, First-Out (LIFO) data structure, where elements are
added and removed from the same end, typically called the "top."
 Operations:
o Push(item): Adds an item to the top of the stack.
o Pop(): Removes and returns the item from the top of the stack.
o Peek(): Returns the item at the top without removing it.
 Example:
python
 stack = Stack()
 stack.push(10)
 stack.push(20)
 print(stack.pop()) # Output: 20

2. Queue:

 Description: A queue is a First-In, First-Out (FIFO) data structure, where elements


are added at the rear and removed from the front.
 Operations:
o Enqueue(item): Adds an item to the rear of the queue.
o Dequeue(): Removes and returns the item from the front of the queue.
o Front(): Returns the item at the front without removing it.
 Example:

java
 Queue<String> queue = new Queue<>();
 queue.enqueue("Alice");
 queue.enqueue("Bob");
 System.out.println(queue.dequeue()); // Output: "Alice"

3. List:

 Description: A list is a collection of elements where each element has a position or


index.
 Operations:
o Insert(item, position): Inserts an item at a specified position.
o Delete(position): Removes the item at a specified position.
o Retrieve(position): Returns the item at a specified position.
 Example:

c++
 List myList = createList();
 insert(myList, 1, 10);
 insert(myList, 2, 20);
 delete(myList, 1);

4. Map (Associative Array):

 Description: A map is a collection of key-value pairs, allowing efficient lookup and


retrieval based on keys.
 Operations:
o Insert(key, value): Associates a value with a specified key.
o Delete(key): Removes the key-value pair associated with the specified key.
o Lookup(key): Retrieves the value associated with the specified key.
 Example:
python
 Map<String, Integer> myMap = new Map<>();
 myMap.insert("Alice", 25);
 myMap.insert("Bob", 30);
 int age = myMap.lookup("Alice"); // Returns 25

5. Set:

 Description: A set is a collection of unique elements with no specific order.


 Operations:
o Add(item): Adds an item to the set.
o Remove(item): Removes an item from the set.
o Contains(item): Checks if the set contains a specific item.
 Example:

javascript
 Set mySet = new Set();
 mySet.add(10);
 mySet.add(20);
 mySet.remove(10);

6. Graph:

 Description: A graph is a collection of nodes connected by edges.


 Operations:
o AddNode(node): Adds a node to the graph.
o AddEdge(node1, node2): Adds an edge between two nodes.
o Traverse(): Performs a traversal of the graph.
 Example:

java
 Graph myGraph = new Graph();
 myGraph.addNode("A");
 myGraph.addNode("B");
 myGraph.addEdge("A", "B");

These examples illustrate the concept of Abstract Data Types by providing a clear interface
for performing operations on various data structures while abstracting away the internal
details of their implementations. The choice of an ADT depends on the specific requirements
of a problem or application.

Q8.Explain about the naming encapsulation?

It seems like your question might be referring to two different concepts: "naming" and
"encapsulation." I'll explain both concepts separately:
Naming:

Naming refers to the process of assigning a name or identifier to a variable, function, class,
or any other entity in a programming language. It plays a crucial role in code readability,
maintainability, and communication among developers. Consistent and meaningful naming
conventions are essential for creating code that is easy to understand and work with.

Here are some general principles for effective naming in programming:

1. Descriptive Names: Choose names that clearly convey the purpose or meaning of the
entity. Avoid overly generic names.
2. Consistency: Follow consistent naming conventions throughout your codebase. This
includes the use of camelCase, snake_case, or any other convention depending on the
language or coding standards.
3. Avoid Ambiguity: Names should be unambiguous, and their meaning should be clear
without the need for additional comments or explanations.
4. Use Pronounceable Names: Choose names that are easy to pronounce and
remember, making communication about the code more straightforward.
5. Avoid Single-Letter Names: Except for loop counters or other well-understood
cases, using single-letter names can be cryptic and should be avoided.

Encapsulation:

Encapsulation is one of the fundamental principles of object-oriented programming (OOP)


that involves bundling the data (attributes or properties) and the methods (functions or
procedures) that operate on the data into a single unit called a class. Encapsulation helps in
hiding the internal details of an object and exposing only what is necessary for the outside
world to interact with it.

Key concepts related to encapsulation:

1. Public and Private Access Modifiers: Encapsulation often involves using access
modifiers to control the visibility of members (attributes and methods) within a class.
Public members are accessible from outside the class, while private members are only
accessible within the class itself.
2. Information Hiding: Encapsulation allows you to hide the internal implementation
details of an object and only expose a well-defined interface. This helps in preventing
unintended interference and allows for easier maintenance.
3. Getter and Setter Methods: Instead of directly accessing or modifying the attributes
of an object, encapsulation encourages the use of getter and setter methods to ensure
controlled access and modification.
4. Data Integrity: Encapsulation helps maintain data integrity by enforcing certain
constraints on how data can be accessed or modified. This is achieved through
encapsulating data and providing controlled interfaces for interactions.

In summary, while naming focuses on giving meaningful names to entities in your code,
encapsulation is a design principle that involves bundling data and methods together to
control access and hide implementation details. Both concepts contribute to writing clean,
readable, and maintainable code.
Q9.Explain about the dynamic scoping.

Dynamic scoping is a method of variable scope resolution in programming languages where


the scope of a variable is determined at runtime, based on the current flow of execution. In
dynamic scoping, the context in which a variable is accessed determines the variable's scope,
rather than the lexical structure of the code (as in static scoping).

Here's how dynamic scoping works:

1. Variable Lookup:
o When a variable is referenced, the interpreter or compiler looks for the
variable in the current scope.
o If the variable is not found in the current scope, the search continues in the
calling function or procedure that invoked the current one.
o This process continues until the variable is found or until the global scope is
reached.
2. Scope Determination at Runtime:
o The determination of a variable's scope happens dynamically during program
execution.
o The scope of a variable is determined by the calling sequence of procedures or
functions.
3. Example:
o Let's consider a simple example in a hypothetical language with dynamic
scoping:

python

3.
o procedure Outer() is
o x = 10
o call Inner()
o end procedure
o
o procedure Inner() is
o print(x)
o end procedure
o
o call Outer()
o
o In dynamic scoping, the Inner procedure, when called from Outer, would
access the variable x from the scope of Outer. The scope is determined by the
calling sequence, so Inner looks for x in the scope of the calling function
(Outer).

Advantages and Disadvantages:

Advantages:

1. Flexibility in Variable Access:


o Dynamic scoping allows for more flexibility in accessing variables, especially
in cases where the calling context is more relevant than the lexical structure.

Disadvantages:

1. Readability and Predictability:


o Dynamic scoping can make code harder to read and understand because the
scope of a variable is not immediately apparent by examining the code. It
depends on the runtime execution path.
2. Debugging Challenges:
o Debugging can be more challenging because the scope of a variable depends
on the runtime call sequence. The value of a variable may change depending
on how a function or procedure is called.
3. Security Concerns:
o Dynamic scoping can introduce security concerns if unintended access to
variables occurs due to unexpected calling sequences.

Dynamic Scoping in Practice:

 Most modern programming languages, such as Python and Java, use static scoping
rather than dynamic scoping. Static scoping is considered more predictable and helps
catch errors at compile-time, providing better code maintainability.
 However, some programming languages, like Emacs Lisp, support dynamic scoping
or allow a combination of both dynamic and lexical scoping.

While dynamic scoping has its advantages in certain scenarios, it's essential to carefully
consider its implications and potential drawbacks, especially in terms of code readability,
predictability, and debugging ease.

Q10. Discuss about the blocks.

n programming languages, a block is a group of statements that are enclosed within curly
braces {}. Blocks serve as a way to group multiple statements into a single compound
statement. The use of blocks is fundamental for controlling the scope of variables, organizing
code, and defining the boundaries of control flow structures. Here are some key aspects of
blocks:

1. Syntax:

 In many programming languages, a block is defined using curly braces {}. The syntax
typically looks like this:

python
 {
 statement1;
 statement2;
 // ...
 statementN;
 }

 The statements within the block are indented for readability, although indentation is
not always a strict requirement in all languages.

2. Scope:

 A block defines a scope for variables. Variables declared within a block are usually
only accessible within that block and its nested blocks.
 The concept of scope is crucial for avoiding naming conflicts and managing the
lifetime of variables.

3. Control Flow Structures:

 Blocks are often associated with control flow structures like conditionals ( if, else),
loops (for, while), and functions/methods. These structures use blocks to group
statements and define their execution boundaries.

python
 if condition:
 # Block of statements for true branch
 statement1;
 statement2;
 else:
 # Block of statements for false branch
 statement3;
 statement4;

4. Function/Method Bodies:

 The body of a function or method is often represented as a block. This block


encapsulates the statements that define the behavior of the function.

java
 void myFunction() {
 // Block of statements
 statement1;
 statement2;
 }

5. Local Variables:

 Variables declared within a block are considered local to that block. They are
typically not accessible outside the block or in nested blocks with the same variable
name.

python
 def myFunction():
 x = 10 # Local variable within the function block
 print(x)

6. Error Handling:

 Blocks are often used in error-handling mechanisms, such as try, catch, and
finally blocks in languages like Python or Java.

python
 try:
 # Block of statements that may raise an exception
 statement1;
 statement2;
 except SomeException as e:
 # Block of statements to handle the exception
 handle_exception(e);
 finally:
 # Block of statements that will be executed regardless of whether
an exception occurs
 cleanup_resources();

7. Lexical Scoping:

 Blocks are closely related to the concept of lexical scoping, where the scope of a
variable is determined by its location in the source code. Lexical scoping helps in
creating predictable and understandable code.

8. Encapsulation:

 Blocks provide a form of encapsulation by grouping statements together. This aids in


organizing code and making it more modular.

Example (in Python):


python
# Example of a block within a function
def example_function():
x = 10
y = 20
if x > y:
# Block of statements
print("x is greater than y")
result = x - y
print("Result:", result)
else:
# Another block of statements
print("y is greater than or equal to x")

# Call the function


example_function()
In this example, the indented blocks following if and else represent the scopes of those
branches, defining the execution boundaries of the respective blocks.

Blocks are fundamental building blocks in programming languages, providing a structured


way to organize code, manage scope, and define the flow of control in a program.

UNIT-IV
Q1.Discuss oop supported in small talk.
Support for OOP in Smalltalk – CO4
Smalltalk is a pure OOP language
– Everything is an object
– All objects have local memory
– All computation is through objects sending messages to objects
– None of the appearances of imperative languages
– All objected are allocated from the heap
– All deallocation is implicit
Type Checking and Polymorphism
– All binding of messages to methods is dynamic
The process is to search the object to which the message is sent for the
method;
if not found, search the superclass, etc. up to the system class which has no
superclass
– The only type checking in Smalltalk is dynamic and the only type error
occurs when a message is sent to an object that has no matching method
Inheritance
– A Smalltalk subclass inherits all of the instance variables, instance methods,
and class methods of its superclass
– All subclasses are subtypes (nothing can be hidden)
– All inheritance is implementation inheritance
– No multiple inheritance
Evaluation of Smalltalk
– The syntax of the language is simple and regular
– Good example of power provided by a small language
– Slow compared with conventional compiled imperative languages
– Dynamic binding allows type errors to go undetected until run time
– Introduced the graphical user interface
– Greatest impact: advancement of OOP
4.7 Support for OOP in C++ - CO4
General Characteristics:
– Evolved from C and SIMULA 67
– Among the most widely used OOP languages
– Mixed typing system
– Constructors and destructors
– Elaborate access controls to class entities
Inheritance
– A class need not be the subclass of any class
– Access controls for members are
– Private (visible only in the class and friends) (disallows subclasses from being
subtypes)
58
– Public (visible in subclasses and clients)
– Protected (visible in the class and in subclasses, but not clients)
In addition, the subclassing process can be declared with access controls
(private or public), which define potential changes in access by subclasses
– Private derivation - inherited public and protected members are private in
the subclasses
– Public derivation public and protected members are also public and
protected in subclasses
Inheritance Example in C++
class base_class {
private:
int a;
float x;
protected:
int b;
float y;
public:
int c;
float z;
};
class subclass_1 : public base_class { … };
// In this one, b and y are protected and
// c and z are public
class subclass_2 : private base_class { … };
// In this one, b, y, c, and z are private,
// and no derived class has access to any
// member of base_class
A member that is not accessible in a subclass (because of private derivation)
can
be declared to be visible there using the scope resolution operator (::), e.g.,
class subclass_3 : private base_class {
base_class :: c;

}
One motivation for using private derivation
– A class provides members that must be visible, so they are defined to be
public members; a derived class adds some new members, but does not want
its clients to see the members of the parent class, even though they had to be
public in the parent class definition
Multiple inheritance is supported
– If there are two inherited members with the same name, they can both be
referenced using the scope resolution operator
Dynamic Binding
– A method can be defined to be virtual, which means that they can be called
through polymorphic variables and dynamically bound to messages
– A pure virtual function has no definition at all
– A class that has at least one pure virtual function is an abstract class
Evaluation
– C++ provides extensive access controls (unlike Smalltalk)
– C++ provides multiple inheritance
– In C++, the programmer must decide at design time which methods will be
statically bound and which must be dynamically bound
Static binding is faster!
– Smalltalk type checking is dynamic (flexible, but somewhat unsafe)
– Because of interpretation and dynamic binding, Smalltalk is ~10 times
slower than C++
59
4.8 Support for OOP in Java – CO4
Because of its close relationship to C++, focus is on the differences from that
language
General Characteristics
– All data are objects except the primitive types
– All primitive types have wrapper classes that store one data value
– All objects are heap-dynamic, are referenced through reference variables,
and most are allocated with new
– A finalize method is implicitly called when the garbage collector is about to
reclaim the storage occupied by the object
Inheritance
– Single inheritance supported only, but there is an abstract class category
that provides some of the benefits of multiple inheritance (interface)
– An interface can include only method declarations and named constants,
e.g.,
public interface Comparable {
public int comparedTo (Object b);}
– Methods can be final (cannot be overriden)
Dynamic Binding
– In Java, all messages are dynamically bound to methods, unless the method
is final (i.e., it cannot be overriden, therefore dynamic binding serves no
purpose)
– Static binding is also used if the methods is static or private both of which
disallow overriding
Several varieties of nested classes
All are hidden from all classes in their package, except for the nesting class
Nested classes can be anonymous
A local nested class is defined in a method of its nesting class
– No access specifier is used
Evaluation
– Design decisions to support OOP are similar to C++
– No support for procedural programming
– No parentless classes
– Dynamic binding is used as “normal” way to bind method calls to method
definitions
– Uses interfaces to provide a simple form of support for multiple inheritance
4.9 Support for OOP in C# -CO4
General characteristics
– Support for OOP similar to Java
– Includes both classes and structs
– Classes are similar to Java‘s classes
– structs are less powerful stack-dynamic constructs (e.g., no inheritance)
Inheritance
– Uses the syntax of C++ for defining classes
– A method inherited from parent class can be replaced in the derived class by
marking its definition with new
– The parent class version can still be called explicitly with the prefix base:
base.Draw()
Dynamic binding
– To allow dynamic binding of method calls to methods:
60
The base class method is marked virtual
The corresponding methods in derived classes are marked override
– Abstract methods are marked abstract and must be implemented in all
subclasses
– All C# classes are ultimately derived from a single root class, Object
Nested Classes
– A C# class that is directly nested in a nesting class behaves like a Java static
nested class
– C# does not support nested classes that behave like the non-static classes of
Java
Evaluation
– C# is the most recently designed C-based OO language
– The differences between C#‘s and Java‘s support for OOP are relatively minor
4.10 Support for OOP in Ada 95 – CO4
General Characteristics
– OOP was one of the most important extensions to Ada 83
– Encapsulation container is a package that defines a tagged type
– A tagged type is one in which every object includes a tag to indicate during
execution its type (the tags are internal)
– Tagged types can be either private types or records
– No constructors or destructors are implicitly called
Inheritance
– Subclasses can be derived from tagged types
– New entities are added to the inherited entities by placing them in a record
definition
– All subclasses are subtypes
– No support for multiple inheritance
A comparable effect can be achieved using generic classes
Example of a Tagged Type
Package Person_Pkg is
type Person is tagged private;
procedure Display(P : in out Person);
private
type Person is tagged
record
Name : String(1..30);
Address : String(1..30);
Age : Integer;
end record;
end Person_Pkg;
with Person_Pkg; use Person_Pkg;
package Student_Pkg is
type Student is new Person with
record
Grade_Point_Average : Float;
Grade_Level : Integer;
end record;
procedure Display (St: in Student);
end Student_Pkg;
// Note: Display is being overridden from Person_Pkg
Dynamic Binding
– Dynamic binding is done using polymorphic variables called classwide types
For the tagged type Prtdon, the classwide type is Person‘ class
– Other bindings are static
61
– Any method may be dynamically bound
– Purely abstract base types can be defined in Ada 95 by including the
reserved word abstract
Evaluation
– Ada offers complete support for OOP
– C++ offers better form of inheritance than Ada
– Ada includes no initialization of objects (e.g., constructors)
– Dynamic binding in C-based OOP languages is restricted to pointers and/or
references to objects; Ada has no such restriction and is thus more
orthogonal

Q2. Explain OOPS supported Ada 65 and Ruby.


General Characteristics
– OOP was one of the most important extensions to Ada 83
– Encapsulation container is a package that defines a tagged type
– A tagged type is one in which every object includes a tag to indicate during
execution its type (the tags are internal)
– Tagged types can be either private types or records
– No constructors or destructors are implicitly called
Inheritance
– Subclasses can be derived from tagged types
– New entities are added to the inherited entities by placing them in a record
definition
– All subclasses are subtypes
– No support for multiple inheritance
A comparable effect can be achieved using generic classes
Example of a Tagged Type
Package Person_Pkg is
type Person is tagged private;
procedure Display(P : in out Person);
private
type Person is tagged
record
Name : String(1..30);
Address : String(1..30);
Age : Integer;
end record;
end Person_Pkg;
with Person_Pkg; use Person_Pkg;
package Student_Pkg is
type Student is new Person with
record
Grade_Point_Average : Float;
Grade_Level : Integer;
end record;
procedure Display (St: in Student);
end Student_Pkg;
// Note: Display is being overridden from Person_Pkg
Dynamic Binding
– Dynamic binding is done using polymorphic variables called classwide types
For the tagged type Prtdon, the classwide type is Person‘ class
– Other bindings are static
61
– Any method may be dynamically bound
– Purely abstract base types can be defined in Ada 95 by including the
reserved word abstract
Evaluation
– Ada offers complete support for OOP
– C++ offers better form of inheritance than Ada
– Ada includes no initialization of objects (e.g., constructors)
– Dynamic binding in C-based OOP languages is restricted to pointers and/or
references to objects; Ada has no such restriction and is thus more
orthogonal

Q3.Briefly explain the subprogram level concurrency.


Subprogram-Level Concurrency
A task or process is a program unit that can be in concurrent execution with
other program units
Tasks differ from ordinary subprograms in that:
– A task may be implicitly started
– When a program unit starts the execution of a task, it is not necessarily
suspended
– When a task‘s execution is completed, control may not return to the caller
Tasks usually work together
Two General Categories of Tasks
Heavyweight tasks execute in their own address space
Lightweight tasks all run in the same address space
A task is disjoint if it does not communicate with or affect the execution of any
other task in the program in any way
Task Synchronization
A mechanism that controls the order in which tasks execute
Two kinds of synchronization
– Cooperation synchronization
– Competition synchronization
Task communication is necessary for synchronization, provided by:
– Shared nonlocal variables
– Parameters
– Message passing
Kinds of synchronization
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
63
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 (approaches
are discussed later)

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
New - created but not yet started
Ready - ready to run but not currently running (no available processor)
Running
Blocked - has been running, but cannot now continue (usually waiting for some
event to occur)
Dead - no longer active in any sense
Liveness and Deadlock
Liveness is a characteristic that a program unit may or may not have
– In sequential code, it means the unit will eventually complete its execution
In a concurrent environment, a task can easily lose its liveness
If all tasks in a concurrent environment lose their liveness, it is called deadlock
Design Issues for Concurrency
Competition and cooperation synchronization
Controlling task scheduling
How and when tasks start and end execution
How and when are tasks created
Methods of Providing Synchronization
Semaphores
Monitors
Message Passing
Q4.Define a task. What are the different states of task?
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 accept
entry_name (formal parameters) do

end entry_name
Example of a Task Body
task body Task_Example is
begin
loop
accept Entry_1 (Item: in Float) do
...
end Entry_1;
end loop;
end Task_Example;
Ada Message Passing Semantics
The task executes to the top of the accept clause and waits for a message
During execution of the accept clause, the sender is suspended
accept parameters can transmit information in either or both directions
Every accept clause has an associated queue to store waiting messages
Figure 6.3 Rendezvous Time Lines
Message Passing: Server/Actor Tasks
A task that has accept clauses, but no other code is called a server task (the
example above is a server task)
A task without accept clauses is called an actor task
– An actor task can send messages to other tasks
– Note: A sender must know the entry name of the receiver, but not vice versa
(asymmetric)
68
Figure 6.4 Graphical Representation of a Rendezvous
Example: Actor Task
task Water_Monitor; -- specificationtask body body Water_Monitor is -- body
begin
loop
if Water_Level > Max_Level
then Sound_Alarm;
end if;
delay 1.0; -- No further execution
-- for at least 1 second
end loop;
end Water_Monitor;
Multiple Entry Points
Tasks can have more than one entry point
– The specification task has an entry clause for each
– The task body has an accept clause for each entry clause, placed in a select
clause, which is in a loop
A Task with Multiple Entries
task body Teller is
loop
select
accept Drive_Up(formal params) do
...
end Drive_Up;
...
or
accept Walk_Up(formal params) do
...
end Walk_Up;
...
end select;
end loop;
end Teller;
Semantics of Tasks with Multiple accept Clauses
If exactly one entry queue is nonempty, choose a message from it
If more than one entry queue is nonempty, choose one, nondeterministically,
from which to accept a message
If all are empty, wait
The construct is often called a selective wait
Extended accept clause - code following the clause, but before the next clause
– Executed concurrently with the caller
69
Cooperation Synchronization with Message Passing
Provided by Guarded accept clauses
when not Full(Buffer) =>
accept Deposit (New_Value) do
An accept clause with a with a when clause is either open or closed
– A clause whose guard is true is called open
– A clause whose guard is false is called closed
– A clause without a guard is always open
Semantics of select with Guarded accept Clauses:
select first checks the guards on all clauses
If exactly one is open, its queue is checked for messages
If more than one are open, non-deterministically choose a queue among them
to
check for messages
If all are closed, it is a runtime error
A select clause can include an else clause to avoid the error
– When the else clause completes, the loop repeats
Example of a Task with Guarded accept Clauses
Note: The station may be out of gas and there may or may not be a position
available in the garage
task Gas_Station_Attendant is
entry Service_Island (Car : Car_Type);
entry Garage (Car : Car_Type);
end Gas_Station_Attendant;
Example of a Task with Guarded accept Clauses
task body Gas_Station_Attendant is
begin
loop
select
when Gas_Available =>
accept Service_Island (Car : Car_Type) do
Fill_With_Gas (Car);
end Service_Island;
or
when Garage_Available =>
accept Garage (Car : Car_Type) do
Fix (Car);
end Garage;
else
Sleep;
end select;
end loop;
end Gas_Station_Attendant;
Competition Synchronization with Message Passing
Modeling mutually exclusive access to shared data
Example--a shared buffer
Encapsulate the buffer and its operations in a task
Competition synchronization is implicit in the semantics of accept clauses
– Only one accept clause in a task can be active at any given time
70
Task Termination
The execution of a task is completed if control has reached the end of its code
body
If a task has created no dependent tasks and is completed, it is terminated
If a task has created dependent tasks and is completed, it is not terminated
until all its dependent tasks are terminated
The terminate Clause
A terminate clause in a select is just a terminate statement
A terminate clause is selected when no accept clause is open
When a terminate is selected in a task, the task is terminated only when its
master and all of the dependents of its master are either completed or are
waiting at a terminate
A block or subprogram is not left until all of its dependent tasks are terminated
Message Passing Priorities
The priority of any task can be set with the pragma priority pragma Priority
(expression);
The priority of a task applies to it only when it is in the task ready queue

Q5.Discuss how producer - commer problem and dining philosophers


problem
are solved using concurrency in Ada.

In Ada, both the Producer-Consumer problem and the Dining Philosophers problem can be
addressed using concurrency features provided by the language. Ada offers tasking constructs
that facilitate the development of concurrent programs. Below are brief explanations of how
each problem can be solved in Ada.

1. Producer-Consumer Problem:

The Producer-Consumer problem involves two types of tasks: producers, which produce
items, and consumers, which consume items. They share a common, bounded buffer. The
challenge is to ensure proper synchronization and mutual exclusion to prevent race
conditions.

Here's a simplified solution using Ada:

ada
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Threading; use Ada.Threading;

procedure Producer_Consumer is
task type Producer is
entry Produce(Item: in Integer);
end Producer;

task type Consumer is


entry Consume(Item: out Integer);
end Consumer;

protected Buffer is
entry Add(Item: in Integer);
entry Remove(Item: out Integer);
private
Data : Integer;
end Buffer;

task body Producer is


begin
for I in 1..10 loop
delay(1.0); -- Simulate production time
Buffer.Add(I);
end loop;
end Producer;

task body Consumer is


Item: Integer;
begin
for I in 1..10 loop
delay(1.0); -- Simulate consumption time
Buffer.Remove(Item);
Put_Line("Consumed: " & Integer'Image(Item));
end loop;
end Consumer;

task body Buffer is


Items : Integer := 0;
begin
loop
select
when Items < 10 =>
accept Add(Item: in Integer) do
Data := Item;
Items := Items + 1;
end Add;
when Items > 0 =>
accept Remove(Item: out Integer) do
Item := Data;
Items := Items - 1;
end Remove;
or
delay 0.1;
end select;
end loop;
end Buffer;

P : Producer;
C : Consumer;

begin
null;
end Producer_Consumer;

In this Ada code, tasks Producer and Consumer share a common buffer implemented using
the Buffer protected type. The Add and Remove entries in the protected type provide
synchronized access to the buffer.

2. Dining Philosophers Problem:


The Dining Philosophers problem involves multiple philosophers sitting at a dining table,
where each philosopher must alternate between thinking and eating. To eat, a philosopher
must pick up both the left and right forks. The challenge is to avoid deadlock and ensure that
philosophers can share forks without conflicts.

Here's a simplified solution using Ada:

ada
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Threading; use Ada.Threading;

procedure Dining_Philosophers is
protected type Fork;
protected type Table;

task type Philosopher(Id: Integer; T: access Table);

protected body Fork is


Taken : Boolean := False;
end Fork;

protected body Table is


Forks : array(1..5) of Fork;
end Table;

task body Philosopher is


use Table;
begin
loop
delay(1.0); -- Simulate thinking time
Put_Line("Philosopher " & Integer'Image(Id) & " is thinking.");

T.Forks(Id).Taken := True;
T.Forks((Id mod 5) + 1).Taken := True;

delay(1.0); -- Simulate eating time


Put_Line("Philosopher " & Integer'Image(Id) & " is eating.");

T.Forks(Id).Taken := False;
T.Forks((Id mod 5) + 1).Taken := False;
end loop;
end Philosopher;

F : Fork;
T : Table;

P1 : Philosopher(Id => 1, T => T'Access);


P2 : Philosopher(Id => 2, T => T'Access);
P3 : Philosopher(Id => 3, T => T'Access);
P4 : Philosopher(Id => 4, T => T'Access);
P5 : Philosopher(Id => 5, T => T'Access);

begin
null;
end Dining_Philosophers;

In this Ada code, the Table protected type defines an array of Fork protected types. Each
Philosopher task alternates between thinking and eating, while ensuring proper
synchronization using the Taken attribute of the Fork protected type. The delay statements
simulate the passage of time during thinking and eating phases.

Both of these examples showcase how Ada's tasking constructs and protected types facilitate
the development of concurrent programs, allowing developers to address synchronization and
mutual exclusion issues in a clear and expressive manner.

Q6. Define a monitor. Explain the features of monitors.


Monitors
Ada, Java, C#
The idea: encapsulate the shared data and its operations to restrict access
A monitor is an abstract data type for shared data
Competition Synchronization
Shared data is resident in the monitor (rather than in the client units)
All access resident in the monitor
66
– Monitor implementation guarantee synchronized access by allowing only one
access at a time
– Calls to monitor procedures are implicitly queued if the monitor is busy at
the time of the call
Cooperation Synchronization
Cooperation between processes is still a programming task
– Programmer must guarantee that a shared buffer does not experience
underflow or overflow

Figure 6.2 Cooperation Synchronization


Evaluation of Monitors
A better way to provide competition synchronization than are semaphores
Semaphores can be used to implement monitors
Monitors can be used to implement semaphores
Support for cooperation synchronization is very similar as with semaphores, so
it has the same problems

Q7.How message passing is implemented in Ada?


Ada Message Passing Semantics
The task executes to the top of the accept clause and waits for a message
During execution of the accept clause, the sender is suspended
accept parameters can transmit information in either or both directions
Every accept clause has an associated queue to store waiting messages

Figure 6.3 Rendezvous Time Lines

Q8.Explain Java threads with example.


Java Threads
The concurrent units in Java are methods named run
– A run method code can be in concurrent execution with other such methods
– The process in which the run methods execute is called a thread
Class myThread extends Thread{
public void run () {…}
}

Thread myTh = new MyThread ();
myTh.start();
Controlling Thread Execution
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 through synchronized statement
synchronized (expression)
statement
Cooperation Synchronization with Java Threads
Cooperation synchronization in Java is achieved via wait, notify, and notifyAll
methods
– All methods are defined in Object, which is the root class in Java, so all
objects inherit them
The wait method must be called in a loop
72
The notify method is called to tell one waiting thread that the event it was
waiting has happened
The notifyAll method awakens all of the threads on the object‘s wait list
Java’s Thread Evaluation
Java‘s support for concurrency is relatively simple but effective
Not as powerful as Ada‘s tasks

Q9.Explain C# threads with examples.


C# Threads
Loosely based on Java but there are significant differences
Basic thread operations
– Any method can run in its own thread
– A thread is created by creating a Thread object
– Creating a thread does not start its concurrent execution; it must be
requested through the Start method
– A thread can be made to wait for another thread to finish with Join
– A thread can be suspended with Sleep
– A thread can be terminated with Abort
Synchronizing Threads
Three ways to synchronize C# threads
– The Interlocked class
Used when the only operations that need to be synchronized are incrementing
or decrementing of an integer
– The lock statement
Used to mark a critical section of code in a thread lock (expression) {… }
– The Monitor class
Provides four methods that can be used to provide more sophisticated
synchronization
C#’s Concurrency Evaluation
An advance over Java threads, e.g., any method can run its own thread
Thread termination is cleaner than in Java

Q10. Explain the design issues of exception handling.

Exception handling is a critical aspect of software development that involves managing and
responding to exceptional conditions or errors that may occur during the execution of a
program. Designing an effective exception handling mechanism requires careful
consideration of various design issues. Here are some key design issues related to exception
handling:

1. Granularity of Exception Handling:

 Issue: Determine the level of granularity at which exceptions are handled. Should
exceptions be caught at a high level, encapsulating large portions of code, or at a more
fine-grained level, catching exceptions closer to where they occur?
 Considerations: Fine-grained exception handling allows for more specific error
recovery and reporting, while coarse-grained handling simplifies the code structure.
2. Exception Propagation:

 Issue: Decide how exceptions should propagate through the call stack. Should
exceptions be propagated up the call stack until caught, or should they be caught and
handled locally within each function or method?
 Considerations: Propagating exceptions up the call stack allows for centralized error
handling, while local handling provides more control over specific error conditions.

3. Error Reporting and Logging:

 Issue: Determine how errors and exceptions are reported and logged. What
information should be included in error messages, and where should error logs be
stored or displayed?
 Considerations: Clear and informative error messages help with debugging. Logging
should capture relevant details such as timestamp, context, and stack trace for
comprehensive analysis.

4. Resource Management:

 Issue: Address how resources (e.g., files, network connections, memory) are managed
in the presence of exceptions. How should resources be released when an exception
occurs?
 Considerations: Use mechanisms like "try-with-resources" to automatically manage
resource cleanup. Ensure proper resource deallocation to avoid resource leaks.

5. Exception Categories and Hierarchies:

 Issue: Organize exceptions into categories or hierarchies based on the types of errors.
How should exception classes or types be structured?
 Considerations: Design a meaningful hierarchy of exception classes to capture
different types of errors. This allows for more specific exception handling based on
the nature of the error.

6. Handling System-Level Exceptions:

 Issue: Determine how to handle system-level exceptions that may arise due to factors
beyond the program's control (e.g., out-of-memory).
 Considerations: Define strategies for gracefully handling system-level exceptions
and potentially logging critical information before the program terminates.

7. Consistency in Exception Handling:

 Issue: Enforce consistency in exception handling across the codebase. Should there
be a standardized approach to exception naming, handling, and documentation?
 Considerations: Consistency improves code maintainability and readability.
Establish coding standards for exception handling conventions.

8. Recovery Mechanisms:
 Issue: Decide on strategies for recovering from exceptions. Can the program recover
from certain exceptions, and if so, how should recovery be attempted?
 Considerations: Some exceptions may allow for recovery strategies (e.g., retrying an
operation), while others may require termination or rollback.

9. Testing and Debugging:

 Issue: Plan for testing and debugging in the presence of exceptions. How can
developers simulate and test exceptional conditions?
 Considerations: Ensure that exceptions are appropriately thrown during testing, and
provide mechanisms for debugging and inspecting exceptions during development.

10. Documentation:

 Issue: Document the exception-handling strategy, including the types of exceptions


that can be thrown, their meanings, and recommended handling practices.
 Considerations: Well-documented exception handling helps developers understand
how to respond to errors and promotes more robust and maintainable code.

Addressing these design issues thoughtfully ensures that exception handling in a program is
effective, maintainable, and aligns with the overall design goals of the software. A well-
designed exception handling mechanism contributes to the reliability and robustness of a
software system.

Q11. Discuss about binary semaphore.


Binary Semaphores
For situations where the data to which access is to be controlled is NOT
encapsulated in a task
task Binary_Semaphore is
entry Wait;
entry release;
end Binary_Semaphore;
task body Binary_Semaphore is
begin
loop
accept Wait;
accept Release;
end loop;
end Binary_Semaphore;
UNIT - V
Q1.What is functional programming?
5.1 Functional Programming Language Introduction – CO5
The design of the imperative languages is based directly on the von Neumann
architecture
– Efficiency is the primary concern, rather than the suitability of the language
for software development
The design of the functional languages is based on mathematical functions
– A solid theoretical basis that is also closer to the user, but relatively
unconcerned with the architecture of the machines on which programs will
run
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 lambda expression specifies the parameter(s) and the mapping of a function in
the following form
(x) x * x * x
for the function cube (x) = x * x * x
Lambda Expressions
Lambda expressions describe nameless functions
Lambda expressions are applied to parameter(s) by placing the parameter(s)
after the expression
e.g., ((x) x * x * x)(2)
which evaluates to 8
Functional Forms
A higher-order function, or functional form, is one that either takes functions as
parameters or yields a function as its result, or both
Function Composition
A functional form that takes two functions as parameters and yields a function
whose value is the first actual parameter function applied to the application of
the second
Form: h f ° g
which means h(x)f(g(x))
For f (x)x + 2 and g (x)3 * x,
hf ° g yields (3 * x)+ 2
Apply-to-all
A functional form that takes a single function as a parameter and yields a list of
values obtained by applying the given function to each element of a list of
parameters
Form:
For h (x) x * x
(h, (2, 3, 4)) yields (4, 9, 16)
5.2 Fundamentals of Functional Programming Languages- CO5
The objective of the design of a FPL is to mimic mathematical functions to the
greatest extent possible
The basic process of computation is fundamentally different in a FPL than in an
imperative language
85
– In an imperative language, operations are done and the results are stored in
variables for later use
– Management of variables is a constant concern and source of complexity for
imperative programming
In an FPL, variables are not necessary, as is the case in mathematics
Referential Transparency
In an FPL, the evaluation of a function always produces the same result given
the same parameters
The First Functional Programming Language : LISP – CO5
LISP Data Types and Structures
Data object types: originally only atoms and lists
List form: parenthesized collections of sublists and/or atoms
e.g., (A B (C D) E)
Originally, LISP was a typeless language
LISP lists are stored internally as single-linked lists

Q2.Write about function composition, construction and apply-to-all in


mathematic functions,
Function Composition
A functional form that takes two functions as parameters and yields a function
whose value is the first actual parameter function applied to the application of
the second
Form: h f ° g
which means h(x)f(g(x))
For f (x)x + 2 and g (x)3 * x,
hf ° g yields (3 * x)+ 2

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 lambda expression specifies the parameter(s) and the mapping of a function in
the following form
(x) x * x * x
for the function cube (x) = x * x * x

Q3.What is meant by logic programming? What are the basic concepts of


declarative structure explain it.

Logic Programming:

Logic programming is a paradigm of computer programming that is based on the principles


of formal logic. In logic programming, programs are written in the form of logical statements,
which declare relationships and constraints that the program must satisfy. One of the most
prominent and widely used logic programming languages is Prolog (Programming in Logic).

Basic Concepts of Declarative Structure in Logic Programming:

1. Declarative Nature:
o Logic programming is often described as a declarative paradigm, where the
programmer specifies what needs to be accomplished rather than specifying
how to achieve it. Declarative programming focuses on expressing the logic
and relationships between entities.
2. Logical Statements (Clauses):
o Programs in logic programming are composed of logical statements or clauses.
A clause can be a fact, a rule, or a query. Facts describe relationships, rules
define how new information can be inferred from existing facts, and queries
seek to find solutions or verify facts.
3. Predicates:
o Predicates are relationships or properties that can be true or false. They are
expressed in terms of facts and rules. Predicates are used to define the logical
structure of the program.
4. Rules:
o Rules specify relationships between different predicates. They consist of a
head and a body. The head declares a new predicate, and the body contains
conditions that must be satisfied for the rule to be applied.

prolog
 parent(john, mary).
parent(john, lisa).
sibling(X, Y) :- parent(Z, X), parent(Z, Y), X \= Y.
In the example, sibling(X, Y) is a rule defining the sibling relationship.

 Facts:

 Facts are basic statements that are assumed to be true. They represent the foundational
knowledge on which rules and queries operate.

prolog
 color(apple, red).
color(orange, orange).

In this example, color(apple, red) is a fact indicating that apples are red.

 Queries:

 Queries are used to ask questions or find solutions in logic programs. They consist of
a predicate with variables that need to be instantiated with values that satisfy the
specified conditions.

prolog
 ?- color(apple, X).

This query seeks to find the color of an apple, and the variable X will be instantiated with the
result.

 Backtracking:

 Logic programming languages, including Prolog, often use backtracking to explore


alternative solutions. If a query fails to find a solution, the system backtracks and
explores other possibilities.

 Unification:

 Unification is a fundamental concept in logic programming where variables in logical


statements are bound to values in a way that satisfies the logical constraints.
Unification allows for the instantiation of variables to make logical statements true.

prolog
 ancestor(X, Y) :- parent(X, Y).
ancestor(X, Y) :- parent(X, Z), ancestor(Z, Y).

In this example, ancestor(X, Y) is defined recursively using unification.

 Horn Clauses:

 Logic programming often uses Horn clauses, which are logical implications in the
form of "head :- body." A Horn clause with an empty body is a fact, and a Horn
clause with a non-empty body is a rule.

prolog
9. grandparent(X, Z) :- parent(X, Y), parent(Y, Z).
10. In this example, grandparent(X, Z) is a Horn clause.

Logic programming languages like Prolog follow these declarative principles, allowing
programmers to express relationships, rules, and queries in a natural and intuitive way. The
execution model of logic programs involves searching for solutions by exploring the logical
relationships defined in the program.

Q4.What are the basic elements in prolog?

In Prolog, a logic programming language, the basic elements include facts, rules, queries,
variables, and predicates. Here's an overview of each of these elements:

1. Facts:
o Facts are the basic statements in Prolog that declare relationships or properties.
They represent information assumed to be true. Facts are written as predicates
with arguments.

prolog
 color(apple, red).
size(apple, small).

In these examples, color/2 and size/2 are facts with two arguments.

 Rules:

 Rules specify relationships between different predicates. They consist of a head and a
body. The head declares a new predicate, and the body contains conditions that must
be satisfied for the rule to be applied.

prolog
 sibling(X, Y) :- parent(Z, X), parent(Z, Y), X \= Y.

In this example, sibling/2 is a rule defining the sibling relationship.

 Queries:

 Queries are used to ask questions or find solutions in Prolog. They consist of a
predicate with variables that need to be instantiated with values that satisfy the
specified conditions.

prolog
 ?- color(apple, X).

This query seeks to find the color of an apple, and the variable X will be instantiated with the
result.

 Variables:
 Variables in Prolog are represented by names starting with an uppercase letter or an
underscore. Variables allow for the generalization of queries and the binding of values
during execution.

prolog
 bigger(X, Y) :- size(X, large), size(Y, small).

In this example, X and Y are variables.

 Predicates:

 Predicates represent relationships or properties in Prolog. They consist of a functor


(the predicate name) and a fixed number of arguments enclosed in parentheses.

prolog
 color(apple, red).
size(apple, small).

In these examples, color/2 and size/2 are predicates.

 Unification:

 Unification is a key concept in Prolog that allows variables in logical statements to be


bound to values in a way that satisfies the logical constraints. Unification is used
during the execution of queries to find values that make the statements true.

prolog
 ancestor(X, Y) :- parent(X, Y).
ancestor(X, Y) :- parent(X, Z), ancestor(Z, Y).

In this example, ancestor/2 is defined using unification.

 Lists:

 Prolog supports lists as a fundamental data structure. Lists are used to represent
sequences of elements. Lists are enclosed in square brackets and can be manipulated
using built-in predicates.

prolog
 colors([red, green, blue]).

In this example, colors/1 is a predicate with a list argument.

 Cut Operator (!):

 The cut operator ! is used in Prolog to control backtracking. It prunes the search space
by committing to the choices made so far, preventing the system from backtracking to
find alternative solutions.

prolog
8. max(X, Y, X) :- X >= Y, !.
9. max(_, Y, Y).
10. In this example, max/3 uses the cut operator to commit to the first rule when X is
greater than or equal to Y.

These elements form the foundation of Prolog programs, allowing developers to express
logical relationships and constraints in a declarative manner. The execution of Prolog
programs involves searching for solutions that satisfy the specified conditions.

Q5. Explain the application of logical programming.

Logical programming, particularly in languages like Prolog, finds applications in various


domains due to its declarative and rule-based nature. Here are some key applications of
logical programming:

1. Artificial Intelligence (AI) and Expert Systems:


o Prolog is widely used in the development of expert systems and knowledge-
based AI applications. Its ability to represent and manipulate facts, rules, and
relationships makes it suitable for encoding and reasoning with knowledge.
2. Natural Language Processing (NLP):
o Logical programming is employed in natural language processing tasks such
as parsing, semantic analysis, and language understanding. Prolog's pattern
matching capabilities make it effective for processing and interpreting natural
language constructs.
3. Database Querying and Management:
o Prolog's querying capabilities are well-suited for database applications. It can
be used to express complex queries and infer information based on rules,
making it applicable in rule-based database systems.
4. Constraint Logic Programming:
o Prolog is often used in constraint logic programming, where logical
constraints are specified, and the system searches for solutions that satisfy
these constraints. This is valuable in optimization problems, scheduling, and
resource allocation.
5. Knowledge Representation and Reasoning:
o Logical programming is employed to represent and reason about knowledge in
various domains. It is used in knowledge bases to encode facts, rules, and
relationships for effective problem-solving and decision-making.
6. Expert Systems in Medicine:
o Prolog has found applications in medical expert systems, where it can
represent medical knowledge, diagnoses, and treatment plans. Its rule-based
nature allows for the encoding of expert knowledge in the form of rules and
facts.
7. Cognitive Modeling:
o Logical programming is used in cognitive modeling to simulate human
cognitive processes. Prolog is employed to express rules that model decision-
making, problem-solving, and reasoning, enabling the study of cognitive
phenomena.
8. Planning and Scheduling:
o Prolog is applied in planning and scheduling applications where tasks,
resources, and constraints need to be managed. Its ability to represent and
reason about relationships makes it valuable in domains such as project
management.
9. Semantic Web and Ontologies:
o Prolog is used in the development of ontologies for the Semantic Web. It helps
in representing and reasoning about complex relationships and knowledge
structures, providing a foundation for the exchange of semantically rich
information.
10. Automated Reasoning:
o Logical programming is employed in automated reasoning systems, where the
goal is to automatically derive conclusions from a set of logical statements.
Prolog's inference engine can be used for tasks such as theorem proving and
logical deduction.
11. Game Playing:
o Prolog has been used in developing game-playing systems where strategic
decisions and rules can be encoded using logical constructs. It allows for the
creation of intelligent agents in game environments.
12. Education and Teaching:
o Prolog is often used in educational settings to teach logic programming
concepts and artificial intelligence. Its declarative nature and ease of
representing knowledge make it a suitable language for teaching logic-based
programming paradigms.

In summary, logical programming, especially in Prolog, is applied in diverse areas where


rule-based reasoning, knowledge representation, and complex relationships play a crucial
role.

Q6. List and explain the key concepts (characteristics) of SL..

It seems there might be a slight confusion in your question. "SL" is a broad term that could
stand for various things depending on the context. Without a specific context or clarification
of what "SL" refers to, I can provide explanations for a few possibilities:

1. Symbolic Logic (SL):


o Key Concepts:
 Propositions: Basic declarative statements that are either true or false.
 Connectives: Logical operators (AND, OR, NOT) used to combine or
modify propositions.
 Truth Tables: Tables showing the possible truth values of compound
propositions.
 Implication: Relationship between propositions where the truth of one
statement guarantees the truth of another.
 Validity and Soundness: Concepts used to evaluate logical arguments
and reasoning.
2. Second Language (SL) in the Context of Language Learning:
o Key Concepts:
 Grammar: The set of rules governing the structure of sentences.
 Vocabulary: The words and phrases in a language.
 Syntax: The arrangement of words to create well-formed sentences.
 Semantics: The meaning of words and sentences.
 Language Skills: Listening, speaking, reading, and writing.
3. Structured Language (SL):
o Key Concepts:
 Syntax: The set of rules governing the structure of statements in a
programming language.
 Semantics: The meaning associated with various constructs in the
language.
 Data Types: The classification of data items, indicating the kind of
values they can hold.
 Control Structures: Statements that control the flow of execution
(e.g., loops, conditionals).
 Modularity: The organization of code into modules or functions.

If you could provide more context or clarification regarding what "SL" specifically refers to,
I would be able to offer more precise information.

Q7. Explain in detail about data types and values in phython language?

In Python, data types and values are fundamental concepts that play a crucial role in
programming. Python is a dynamically typed language, which means you don't need to
declare the data type of a variable explicitly. The interpreter infers the type based on the
value assigned to it. Here's an explanation of various data types and values in Python:

1. Numeric Types:

a. int (Integer):

 Represents whole numbers (positive or negative).


 Example: x = 5

b. float (Floating-point):

 Represents real numbers with a decimal point.


 Example: y = 3.14

c. complex (Complex):

 Represents complex numbers in the form a + bj.


 Example: z = 2 + 3j

2. Sequence Types:

a. str (String):

 Represents a sequence of characters.


 Example: text = "Hello, Python"

b. list:

 Represents an ordered, mutable sequence of elements.


 Example: my_list = [1, 2, 3, 'four']

c. tuple:

 Represents an ordered, immutable sequence of elements.


 Example: my_tuple = (1, 2, 3, 'four')

3. Set Types:

a. set:

 Represents an unordered collection of unique elements.


 Example: my_set = {1, 2, 3}

b. frozenset:

 Represents an immutable set.


 Example: frozen_set = frozenset([1, 2, 3])

4. Mapping Type:

a. dict (Dictionary):

 Represents an unordered collection of key-value pairs.


 Example: my_dict = {'name': 'John', 'age': 25}

5. Boolean Type:

a. bool (Boolean):

 Represents the truth values True or False.


 Example: is_valid = True

6. None Type:

a. NoneType:

 Represents the absence of a value or a null value.


 Example: empty_variable = None

Key Characteristics:

1. Dynamic Typing:
o Python is dynamically typed, meaning you don't have to specify the type of a
variable explicitly. The interpreter infers it based on the assigned value.
2. Type Conversion:
o You can convert between different data types using built-in functions like int(),
float(), str(), etc.
python
 x = 5
y = float(x) # Convert integer to float
z = str(x) # Convert integer to string

 Mutable vs. Immutable:

 Some data types, like lists and dictionaries, are mutable, meaning their values can be
changed after creation. Others, like tuples and strings, are immutable.

python
 my_list = [1, 2, 3]
my_list[0] = 10 # Valid for lists (mutable)

my_tuple = (1, 2, 3)
my_tuple[0] = 10 # Invalid for tuples (immutable)

 Type Checking:

 You can use the type() function to check the type of a variable.

python
 x = 5
print(type(x)) # Output: <class 'int'>

 Type Annotations (Optional):

 Python supports optional type annotations using the typing module, introduced in Python
3.5.

python
5. from typing import List, Tuple
6.
7. def my_function(values: List[int]) -> Tuple[int, int]:
8. # Function body
9.

Understanding data types and values is crucial for writing correct and efficient Python code.
Python's flexibility in handling various types allows for versatile and readable programming.

Q8. Give a brief account of python variables, storage and contol.

Python Variables:

1. Definition:
o A variable in Python is a symbolic name that refers to a value or an object.
Variables are used to store and manage data within a program.
2. Dynamic Typing:
o Python is dynamically typed, meaning you don't need to declare the type of a
variable explicitly. The interpreter infers the type based on the assigned value.
python
 x = 5 # x is an integer
y = "hello" # y is a string

 Variable Naming Rules:

 Variable names can contain letters, numbers, and underscores.


 They cannot start with a number.
 Python follows a case-sensitive naming convention.

python
3. age = 25
4. user_name = "John"
5.

Storage in Python:

1. Memory Management:
o Python manages memory automatically using a mechanism called garbage
collection. Memory is allocated and deallocated as needed.
2. Object References:
o Variables in Python are references to objects in memory. When a variable is
assigned a value, it references the memory location where the object is stored.

python
 x = 10 # x references the memory location of the integer object 10

 Immutable vs. Mutable:

 Immutable objects (e.g., integers, strings, tuples) cannot be changed after creation.
 Mutable objects (e.g., lists, dictionaries) can be modified.

python
3. # Immutable
4. x = 5
5. x = x + 1 # Creates a new integer object, x now references the new
object
6.
7. # Mutable
8. my_list = [1, 2, 3]
9. my_list[0] = 10 # Modifies the existing list in-place
10.

Control in Python:

1. Conditional Statements:
o Python supports if, elif, and else statements for conditional execution.

python
 x = 10
if x > 0:
print("Positive")
elif x < 0:
print("Negative")
else:
print("Zero")

 Loops:

 Python provides for and while loops for iterating over sequences or executing code
repeatedly.

python
 # For loop
for i in range(5):
print(i)

# While loop
x = 0
while x < 5:
print(x)
x += 1

 Functions:

 Functions allow you to define reusable blocks of code.

python
 def add_numbers(a, b):
return a + b

result = add_numbers(3, 7)
print(result) # Output: 10

 Exception Handling:

 Python uses try, except, else, and finally blocks for handling exceptions.

python
 try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero.")

 Modules and Packages:

 Python allows you to organize code into modules and packages for better structure
and reusability.

python
5. # Module
6. # math_operations.py
7. def add(a, b):
8. return a + b
9.
10. # main.py
11. from math_operations import add
12. result = add(3, 5)
13.

Python's variable management, memory handling, and control structures contribute to its
flexibility and readability. Understanding these concepts is essential for writing efficient and
maintainable Python code.

Q9. Explain the concept of bindings and scope in python language.


A PYTHON program consists of a number of modules, which may be grouped
into packages.
Within a module we may initialize variables, define procedures, and declare
classes. Within a procedure we may initialize local variables and define local
procedures. Within a class we may initialize variable components and define
procedures (methods).
During a PYTHON session, we may interactively issue declarations, commands,
and expressions from the keyboard.
These are all acted upon immediately. Whenever we issue an expression, its
value is displayed on the screen. We may also import a named module (or
selected components of it) at any time.
PYTHON was originally a dynamically-scoped language, but it is now statically
scoped.

In Python, bindings and scope are fundamental concepts related to how variables are assigned
and accessed within a program. Let's explore these concepts in detail:

Bindings:

1. Definition:
o A binding in Python refers to the association of a name (variable) with a value
(object). When you create a variable and assign it a value, you are creating a
binding between the variable name and the object in memory.

python
 x = 5 # 'x' is bound to the integer object 5

 Dynamic Typing:

 Python is dynamically typed, meaning you can reassign a variable to a different type.

python
 x = 5 # 'x' is initially bound to the integer object 5
x = "hello" # 'x' is now bound to the string object "hello"
 Multiple Bindings to the Same Value:

 Multiple variables can be bound to the same value in memory.

python
 x = y = 10 # 'x' and 'y' are both bound to the integer object 10

 Binding with Different Types:

 You can bind the same variable to objects of different types.

python
4. x = 5 # 'x' is bound to the integer object 5
5. x = "hello" # 'x' is now bound to the string object "hello"
6.

Scope:

1. Definition:
o Scope refers to the region of code where a variable is accessible. In Python,
variables have either global or local scope.
2. Global Scope:
o Variables defined outside any function or block have a global scope. They are
accessible throughout the entire program.

python
 global_var = 10

def my_function():
print(global_var)

my_function() # Output: 10

 Local Scope:

 Variables defined within a function or a block have local scope. They are only
accessible within that function or block.

python
 def my_function():
local_var = 5
print(local_var)

my_function() # Output: 5

 LEGB Rule:

 Python follows the LEGB (Local, Enclosing, Global, Built-in) rule to determine the
scope of a variable. When a variable is referenced, Python looks for it in the following
order: Local, Enclosing (if inside a function), Global, and Built-in.

python
 x = 10 # Global scope
def my_function():
x = 5 # Local scope
print(x)

my_function() # Output: 5

 Nonlocal Keyword:

 The nonlocal keyword allows you to modify a variable in an enclosing (non-global)


scope.

python
5. def outer_function():
6. x = 10 # Enclosing scope
7.
8. def inner_function():
9. nonlocal x
10. x = 5
11.
12. inner_function()
13. print(x) # Output: 5
14.
15. outer_function()
16.

Understanding bindings and scope is crucial for writing maintainable and error-free Python
code. It helps you manage variable assignments and access in a way that aligns with the
structure and requirements of your program.

ChatGPT can mak

Q10. Explain the concept modules in data abstraction in python languages.


Data Abstraction
PYTHON has three different constructs relevant to data abstraction: packages,
modules, and classes.
Modules and classes support encapsulation, using a naming convention to
distinguish between public and private components.
A package is simply a group of modules. A module is a group of components
that may be variables, procedures, and classes.
These components may be imported for use by any other module. All
components of a module are public, except those whose identifiers start with ‘‘_’’
which are private.
A class is a group of components that may be class variables, class methods,
and instance methods. A procedure defined in a class declaration acts as an
instance method if its first formal parameter is named self and refers to an
object of the class being declared. Otherwise the procedure acts as a class
method.
To achieve the effect of a constructor, we usually equip each class with an
initialization method named ‘‘__init__’’; this method is automatically called when
an object of the class is constructed. Instance variables are named using the
usual ‘‘.’’ Notation (as in self.attr), and they may be initialized by the
initialization method or by any other method. All components of a class are
public, except those whose identifiers start with ‘‘__’’, which are private.

You might also like