[go: up one dir, main page]

0% found this document useful (0 votes)
110 views25 pages

PPL Unit 1 and 2 Decode Scan

Uploaded by

G K
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)
110 views25 pages

PPL Unit 1 and 2 Decode Scan

Uploaded by

G K
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/ 25

comme tn to

stng
loop

Control
Veriebles
Inslde
the for
Labeled
Continue).
String
Handine
String
and
Loop Breab

Programming Language
iabeted

using Java
Stetements

1
E n c a p s u l a t i o n

methods
astia
gning Syntax and Semantics
Polymorphism,

I n h e r t a n c e ,
declaring
objects
V constris.
UNIT
fundementals.

returning
& ralue. ructon
MethodsCles
class. methode
to t
Cesses end Puh
methods orerloeding

addtng
rertables
finalire0
method.

control.
static. final. nested
final

nts Inherttar cesthe


reference
colection eccess

objects
kerrord
gerhage returning
rarieble-length
arguments
Language and Software Development Environments
obiect as
perameter.
erquments. Using super. multu
1.1:
pesting ine references.

commend
clas de
tmner
clesses super dynamic method
ftware development process.
tnheritence.
orerriding.
and method
package term software
Defining a Definethe
acoess
Member

cal sequence Interfeces:

end (defn 1
combination of
c o n s t r u c t o r

interfaces
hiererchy

ining is a sequential
Software development process
Pacbages packages,
Obiect cles
ebrtract
ciesses
access
protection.
Importng
intertaces, ding inte
extending inter
nterface and at
CLASSPATH in Ans.
well defined starting and ending points
each having
end rariebles
pecheges
nesting
appiring). phases, each
tmpiementetior

there are identifiable


deliverables to the next phase.
tnstence of operetor phase
each
in Java software development process in brief.
UNIT VI Exception Handling catch. throw.
throws, finel Explain
ay. Q.2
ypes. uncaught
exceptions,
custom except
exception
built-in exceptions.
exception exceptions.
Fundementel

cleuses nested ty
statements.
Streams. byte Streams and Ans.
multiple catch Vo:
own exception
sub ciasses). Managing console input. Writng Console Requirement

analysis & specification


creeting o u r
Streams. Reading
Predetined Architecture, Appler
Fundamental. Applet
Characte Streems

Output Print Writer ciass. Appiet Apple:


HTML Applet tag. passing parameten
L Sofware design
status window. and specification
Sbeleton. Requesting Repeinting.
Program.
to Appiets Difierence
berweer Applet and Application
Implementation

Verification
and validation

Testing

Maintenance

Fig.Q.2.1 Phases ofsoftware development process


(1) Requlrements Analysis and Specification
documented in
identified and
The requirements of the system are

this phase.
a document
which is
then documented in
nese requirements are Specification (SRS).
popularly known as Software Requirement
1-2 Pyog Lenguage Smtar and Se
PPL
Specification 1-3 Prgramntng Lamgusge Synter end Semania
(2 Sofhware Design and
and specificati 1.2 Language and Software Destgn Methods
The SRS is used during the software design ation
During this phase. various software modules
and their interfa
Important Points to Remember
designed The programming languages have some programming constructs
3) Implementation using which particular software design method canbe
impiementation is a phase in which the coding i5 done in suitah implemented easily.
language with the help of design document. Some languages can be
programming implemented with the heip of objects.
Idealy it shoukd be simply mapping of software design intot Such languages are called object oriented
programming
coresponding code. language. For example -C, Java
4 Verification and Validation Similary Pascal or C are structured programming languages.
03 What do you mean by programming paradigm?
This phase is for checking the quality of the software system being Ans.: The programming paradigm represents a specific programming
deveioped style suitable for implement specific software design methodd
Verificeion means "Are we
building the product right?" and Q4 Explain the styles ofsoftware design.
validaion mezns "Are we building the
right product". Ans.
(5) Testing Procedurai programming

Testing is a process of finding bugs or errors from the Functionai programming


system.
(6) Maintenance
Abstract data type programming
After delivering th software sysem to the user, there Software
for are chances design Modue based programming
changes in the sysem due to Some methods
soTe dditional funcionality. malfunctioning or due to
Object onented programming
.This cost of maintenarce is always higher than all other
software development phases. the Generic programming

Decaratve programming
Fig Q.4.1 Styles of software design
nd Se.
Programming Language Syntax and Seman
1-4
Semantics
1-5 Programmng Language Syntax and
PPL

Programming
1he focus of this stv PPL
1)Procedural and functions.
1.3 Languages and Computer Architecture
is on procedures
programming language
This programming style is mainly
ma.
Programming:
(2)Functional functions. The expressions.
and ns Important Points to Remember
applicable for of mathematical
use
architecture in computer is
blocks of this programmin The most commonly used computer
building
functions are the primary
Haskell, ML are
the examples similar to Von Neumann architecture.
Programming languages like of CPU, Memory Unit,
The Von Neumann architecture consists
functional programming
When the abstract data type Input deviceand Output device.
(3)Abstract Data Type Programming: then this style is used. CLU Q.5 Explain with diagram
the relationship between languages
and

is the unit of programming modularity architecture.


computer
makes used of this type of programming,
programming language
Ans.
(4)Module Based Programming: In
this style of programming, the Programmers need
fundamental unit is module. Each module is comprised of Requirements

variables, functions, procedures and so on. These modules can be Programming languages
primarily used to export the services from one module to another.
Modula-2 and ADA are two commonly used programming Imperative languages

languages that use module based programming

(5)0bject Oriented Programming : The emphasis of this style is Procedural Module Object Generic
Towards
high level
based oriented
objects. Examples are C+, Java, ADA-95 and so on. programming

(6)Generic Programming : In this type of programming style, the


generic modules are instantiated during compile time Functional programming
or run time
and various entities like data structures, Tunctions or procedures are Logic programming
created.

(7)Declarative Programming: In this style of programming, there is Constraints


declarative description of problem instead of
algorithmic Von Neumann architecture
implementation. For example Logic programming technia1e
-

in programming language like can architecture


be implemented PROLOG. Fig Q.5.1 Programming languages and machine
Conventional programming languages are implemented on the Von
Neumann architecture. These languages are also called as Von
1-6 Programming Language Syntax and
and SemaN
PPL
Programming Language Syntax
and Semantics
used for these lann. 1-7
Neumann languages. The
other termms

based languages
or statement based
u
anguages
lan
PPL
the algorithm of the
languao3) Simplicity: Due simplicity increases the readability of the
to
program
can

also called as state


The simplicity
The systematic development of these languages is to be expressed easily.
going
program.
constructs that should be
high level of abstraction. Safety: There are some
programming
other type oflanguages (4) is harmful in
Along with the imperative languages prohibited. For example use of gotos
*sustrictly
strictly flexibility and
programmingg languages are also execu. These features may reduce the
as Functional and Logic Clprogramming
on Von Neumann architecture. Following Fig. Q.5.I represents readability of the program.
which
relationship between languages and computer architecture. Robustness: Robustness is a feature of a
program
(5) events in program. In
to deal with undesired
14 Programming Language Qualities provides the ability and suitable
some undesirable situations, the event is trapped
so that system becomes predictable
response can be programmed
Q6 Write and explain various language qualities that promote for the m
reliability of a language.
1undesirable situations.
achieve the efficiency.
Ans. Q.7 Explain how any language can
Language qualities
Ans.:
More execuion speed

Writability Readability Simplicity Safety


Robustness
Fig. Q6.1 Language qualites that Less memory consumption
support rellablity
(1)Writability Efficiency
can
It is a be achieved
property of expressing a program in a Ost
most natural Reusability
Writability should focus on problem sol
Wntability should focus on problem natural way.
way
not be distracted by solving activity and should
language
details.
(2) Readablity Portability
Due to English text and familiar
notations
tions the Fig.Q.7.1 Language and efficiency
programming languages is increased. For exampleddability readah of
statements there is a use of if-then-else The most desired feature of a language is efficiency. The basic goal
the loopingg statements there are construct. Fo conditional
of such
for,while and repre
do-whiesenting of efficiency is program execution should be faster and it should
programming constructs enhance the reada loops.Use consume less memory.
understandability of the program. bility and Other aspects of efficiency are reusability and portability.
nfax and
Programming Language Syntar and SemaPPL ProgrammingLanguage Syntax and
Semantics
1-8 1-9
PPL used to
the software develo the rules that are

Reusability : For language efficiency elope


PEtQ.9 is syntax of language ? Explain
What
that e sdefine the syntax of a language.
are
a

such components
in developing form
always interested
Ans.: Syntax is defines as a collection of rules that define the
for other applications.
is a feature by which the program o f alanguage. of rules: lexical
.Portability: Portability is defined by two set
other
m The syntax of language
a
modified to work on platfom
work on one platform can be
rule and syntactic rules.
Perspective and Early specific word classes.
That
1.5 A Brief Historical
The lexical rules affect in particular
High Level Languages of characters that
rules specify the rule for set
means, the lexical
scanf,
form a word. For example do, if, print,
-

can be combined to
level language along with their. use lexical rule.
Q.8 Enlist any four high
are all keywords in C.
This can be specified using the
purpose. which defined the particular
The syntactical rule has a wider scope
Ans.
defined by the lexical rule.
arrangement of words
Language Originator Year Purpose the context free grammar
For specifying the syntax of a language
COBOL Committee 1960 BusinessData Processing is used.
with the help of suitable
Q.10 Explain the concept of syntax diagrams
Pascal N.Wirth 1971 General Purpose
example.
the lexical rule and syntactic rules
D. Ritchie 1974 System Programming Ans.: Following example shows
for a simple program containing a_signment
statements only.
ADA J.Ichbiah 1979 General Purpose,
Embedde syntactic
ynt Rule
System
program> : = { <statement>*}
statement> :=<assignment>
<assignment> :=<identifier>=<expr>;
1.6 Language Definition
Kexpr>:=<identifier>| <number> |(<expr>)| <expr> <operator>
<expr>
Important points to Remember Lexical Rule
Every programming language has two major Com
Syntax and Semantics. ntsoperator> :=+|-|°|/|<|>|<=|>=
<identifier> :=<letter> <ld>*
Syntax represents form of a language | <digit>
kld>: <letter>
Semantic represents the meaning of alanguage.
PPL 1-10 Programming Lang1uage Syntar o
nd Sem
<number> := <digit> + 1-11 Programming LanguageSyntax and SemanticCS
PPL
<letter::= a|blc|...|z For example consider the C code fragment
<digit> := 0|1|2|....|9
The above rules can be represented using syntax diagra for(i=0;i<=10;i++)

The non terminals are represented by circles.


ram
Terminals are represented by boxes.
Now consider Pascal Code fragment for for loop
For i=0 to 10 do

program - 0 Begin

End
Thus these two constructs differ only at lexical level
statement concrete syntax specifications incude
Concrete Syntax : The
the tokens and keywords that allow parser to construct aan
a
statementassignment abstract syntax tree unambiguously. The concrete syntax tree will
retain all the information of input
assignment
identferE
0 + expr For example
expr Consider the context free grammar
expr operator expr E: E-+E
E = E*E
identifier E:num
The expression 2*3+4 can be derived aas

number

expr

Fig. Q.10.1: Syntax


-0-
diagrams
Q.11 What is abstract syntax and
conerete
suitable examples. syntax ? Abstract syntax Concrete syntax
Ans.
Explain w tree tree
Abstract Syntax:
When the two
lexical level then it is said that constructs dist
they have abstract syntax,
unguage Syntar.
axiomatic and denotational
ntax and Se
Q.12 Explain
example.
emantics with
sema.

Semantics
1-13 Programming Language Syntax and
Ans.: 1) Axiomatic Semantic PPL
Let,
.The axiomatic semantic is a semantic that is that is appropriatb a = expr
will be
arguing program correctness.
assignment statement. Then denotational semantic
be an
An axiomatic semantic consists of specified as
f) error for undefined variable in expr.
i) A language for stating assertions about programs. i) dsem (a:
=
expr, =

result
expr, f) =

i)dsem (a:
=

i) Rules for establishing the truth


ofassertions. and S2 to be executed as

The assertions be made


Ifthere are two statements S1
can by using a triple called Hoare .
for example Hoare Thi 1 $1;52
<Pre> C <Post> dsem (S1, 1 = f1.

Where C is a command <Pre> and


represents f1) 2
dsem(S2,
=

condition before execution of precondition ie.


command. The
postcondition i.e. the condition after execution of<Post> represents s dsem ($1:S2,undefined
1)1 variable
..hle error will be propagated.
error will
For example command. For any propaga
{b 5) Q.13 What is pragmatics?
a5 b+2 a> 1) formal specification of
Ans. Pragmatics does not affect the
focuses on design ofa
programming languages. However, pragmatic
Precondition Command that it would be easy to read,
programming language in such a way
The
preconditions and postconditionsPostconditon
are write, and modify efficiently. Pragmatics
describes how to use the
2. Denotational semantic
presented in braces.
This is another
prac situations.
language in practical
method of Forexample:
This method based on scribing semantic of
if(a>b)
.For
recursive functions programs.
instead of predicate.
instead aat10;
example Consider an
expr. The function
f(expr)
assignment
gives eror ifif itstatemene
In above code there is single statement
to be executed hence we ,

it isis for
expression But if there are more than single line
statements
variablex present in expr. Otherwiseexpr undefined apression not used {}.
have not t
result of evaluation will be will ined, Or
for sam
same then we have to enclose them within {}. There are chances to forget
then have to
returned. be we
en
evaluated and to add brackets for execution of multiple
statements. Hence

line statement also within


pragmatically C allows execution of single
DECODE Less than gHOTOca {and .
PPL 1-14 Programming Language Syntax and.s
and Sema
Q.14 : - 2*y +1 1-15 Programuming Language Syntax and Semantics
yX-3 2.15 Gtve advantages and disadvantages of interpretation.
ns.
0
assignment statement,
Compute weakest precondition for given Advantages
Ans.: For the given assignment statements y < 0) is assod.
a . Modification of user program can be easily made and implemented
postcondition.
as execution proceeds.
Let y:X-3
.Type of object that denotes a variable may change dynamically.
but y <0 is given posteondition. Substinuung l l0r
cuauon 1, w,
Debugging program and finding task for
get
a errors is simplified a

program used for interpretation.


X-3 < 0
.The interpreter for the language makes it machine independent.
X<3
Weakest precondition for first isadvantages:
assignment statement.
Now consider . The execution ofthe program is slower.
x: 2*y+1 ..Memory consumption is more.
Substitute x<3 for equation 2,
2.16 What is translation?
2*y+1 < 3
Ans. Translation is a process in which the high level program is
2y< 2
translated into the machine language code before getting executed.
y<IWeakest precondition for second assignme
The high level languages like C, C++need
statement. translaion.
Q.17 Explain language processing using translation.
1.7 Language Processing, Interpretation,
Translation, the Concept of Binding
Ans.: The process oftranslation is performed in followingsteps-
I. The program modules are separately translated into relocatable

ImportantPoints to Remember machine code. This translator is called as compiler.


.Language processing can be performed sing These translated modules are linked together in a relocatable unit
1.
Interpretation and Translation. two alternatives This task is carried out by linker or linkage editor.
-

During interpretation of a language, every .Finally the complete program is loaded into the memory as
instruction is
executed. directly executable machine code. This task is carried out by loader.
Translators can be compilers and
assemblers
Programming Language Syntax and Seman 1-17 Programming Language Syntax and Semantics
1-16 PPL
PPL Source
The interpreters do not The compilers produce
program 2.
produce object code. object code.

Demerit: The compilers


Complier

3. Merit: The interpreters can


Relocatable
has to be present on the
machine code be made portal because they
do not produce object code. host machine when
Linker particular program needs
Single relocatable
to be compiled.
unit

4. Merit Interpreters are Demerit: The compileris


Loader it
simpler and give us a complex program and
Executable
improved debugging requires large amount of
unit
environment. memory.
Output data
Inputdata Interpreter
(executed Q.19 Explain the concept of binding.
result) variables,
contain various entities such as
Ans. Any program
using translation
routines, control statements and These entities have special
Fig. Q.17.1: Language processing
so on.

For example
uses the combined two techni properties. These properties are called attributes.
The modern translation technique has number of
-translation and then interpretation. That means the source codethe
programming entity routine or function
methods and so
intermediate code and then the intermediate code parameters, type of parameters, parameter passing
translated into
on. Specifying the nature of attributes is called binding.
interpreted.
stored in data structure called
Q.18 Diferentiate betwen- Interpreter and compiler. The attribute description is a

Ans. descriptor.
Sr. No. The binding can be of two types static binding and dynamic
Interpreter Compiler
1.
binding
Demerit The source Merit: In the process When the attributes are bound at program translation time then it is
program gets interpreted
compilation the prog called static binding.
every time it is to be is
analyzed only once a When the attributes are bound at program execution time then it is
executed, and every time the then the code
source is called dynamic binding.
program analyzed. generated. Hen
Hence interpretation is
efficient than Ca
less compiler is efficient th
Programming Lang
I-18
PPL 1-19 Programming Language Syntax and Semantics
PPL 1.81.8 Varlables

In above code, there are three variables namely a,b and c. These
variables have the scope for entire function sum0. Outside the
Remember

Important
Pointsto function sum), these variables are not visible or accessible.
ofmemory
memory in which
which
name
for
reserved
area
som 2) Type
Variable is a

be stored. the hel be defined specification of set of values that


value can
an be modified
modified with
help Type can as can be
variable can
The values in associated with a variable. For example -

assignment statements.
char s;
attributes of variables
Q.20 Explain various Here the variable s is of type character. That means it allows the
Ans. value range from -128 to 127

Various attributes of
variables are
The language defines its in-built set of data types. These types are

Name and Scope called primitive types.


1)
the declaration statem. 3) 1-value
The variable name is introduced during
For example in C The term lvalue originally referred to objects that appear on the left
int a; (hence the 1') hand side of an expression. An lvalue represents an
location in memory
Here the variable namea is specified at declaration statement. object that occupies some identifiable
For example
The scope of the variable is basically the area of instructions
nt x
which the variable name is known. The variable is visible under1
name within its scope and is invisible under the name outside Here variable x is a lvalue, because it is an object with an
scope. For example identifiable memory location.
void main()
4) r-value
sum(); The value is encoded value which can be stored in the location
r
}
void sum) associated with the l-value variable. The encoded representation is
interpreted according to the variable's type.
int a,b.c; For example
a=10;b=20; int x
c=a+b;
K=(3+4);
printf"in The sum= %d",c); The value of (3+4) represents the r-value.
Programming
Syntax and
Language Syntax
and SemeyPPL 1-31 ProgrummingLangnage Symtax and Semanties
setuat
varinbles
? parameter
unnnmed
votd main ()
PPL
What are
referenee
mnd
are
those
variables that
hat can
Q.21
variables Such a
unnaned variable.
Declarafon
Am. The
r-value ofanother
void aum (int a, int b|
accessed
through

called as reference.

be
accessed using pointer to poin sum (10, 20) Call
can
variable
unnamed
The
variable declare a variable of noi.

we can
In pascal the up-arTo void sum (int x, int y)
For exampie rrow
defined by pretixing
type is
integer. The pointer
with the base type. formal parameter
caret symbol (") n a m e d type because int 2
a is of Defnitton
/here variable
type a integer /accompanied with type
printi'Addition %d"', z)
and pointed by a
allocate an unnamed integer variable
We can

of type a
Q.23 Explain the positional method of binding.
newlaPtr): //unnamed varnable

The languages like C, C+ allow pointer


to rerer o namAns.: Most of the programming languages use positional method for
binding actual to
variables. For example-
void main()
intx=6.//integer named variable formal parameters Actual parameters
nt "ptr. //pointer vanabie in routine call.
ptr=&x //using & the reference variable is represented.
Following Sum (a, b, c) Functlon call
1.9 Routines FigQ.23.1 Binding of
represents formai and actual
parameters
Q.22 What are routines ? Explain how routines can be handled ? positional method
Functdon definiton
Ans.:Routine is a collection of instructions that can be use of binding in which oid
sum
(int x, int y, int 2)

perform specific task and can be repeatedly executed. For examp is parameter a is
Functions in C, Assembly language bound to parameter Formal parameters
subprograms, the subroutines
in FORTRAN, Procedures and x, parameter b is
Functions in Pascal and Ada.
The routines are usually handled by three ways bound to parameter
i) Declaration ii) call y and so on. Fig. Q.23.1 Positional method of binding
ii) definition For
Programmlng
Language nd Sem
Syntara n

1-22 PPL 1-23 ProgrammingLanguage Syntax and Semantics


routines.

PPL of generic
the
concept which implements the
implements
the des 1.10 An Abstract Semantic Process
. 2 4 Explain
routineisa
routine

concept
the concept of
of gen
In C++,
Am.:Generic

data type.
using
general .26 Write short note on abstract semantie processor.
algorithm templates.

outine is
achieved by using above code
code c a n be
can imn
be implemen Ans.: The abstract semantic processori is an abstract processor
C++ the above
In
kor example
follows
used for describing the operational semantics of programming
routine as
using generic
languages.
template <class T>
.It consists of instruction pointer, memoryand processor
T add(T a. Tb) The memory is a part where the instruction is executed and data to
be manipulated are stored. The memory is divided into two parts -
TC
Ca+b code memory and data memory. The code memory is denoted by
return c; array C[location_Index] and data memory is denoted by array

Q.25 What is aliasing ? Explain with


suitable example. D[location_Index
which two dife The C[I and D[!] denote the values stored in Ith cell of code and
Ans.: Definition: Aliasing is a mechanism by data memory respectively.
names are associated with the same entity. The concept of alias
is exactly opposite to that of overloading. The instruction pointer(ip) always points to the code memory(C)
The modification of value stored
For example
at particular cell is done using the
instruction set.
void fun(int &a)
The read instruction is used to read the value îrom
input device
cout << "Value is:" <<a; and write is used to write the instructions to the
output device.
For example
void main()
set 50, read
int x = 10; The
meaning this command is read from the input device and is stored
val
fun(x) a t location 50
10 1024 102
set write, D[20]
Here two different 1024 1090 1090
variables x The meaning of this command would be value stored
and a point to the at location 20
i.e. 10
same value will be transferred to the
int val;
output device.
The aliasing can be easily The jump instruction is used to
val 10; modify the usual control flow. The
achieved using int a &val; val,a,b ard alises jump instruction has two versions jump (unconditional jump) and
example
pointers for int b &val;
-

jumpt(based on condition)
Fig. Q.25.1
Syntarand

1-24
Programming
Language
Semam
polnter PPL 1-25 Programming Language Syntaxand Semantics
PPL
I n s t r u c t i o n

Memory
instruction
pointer | Hence there are three allocation methods used during run time
The the
to structure. These are
points
always
code
instruction in the 1. Static allocation The static allocation is for all the data objects at
memory. compile time.
Following Fig. Q,26.l
2. Stack allocation In the stack allocation astack is used to manage
machine shows abstract
the run time storage.
machine Code memory Data memon 3. Heap allocation In heap allocation the heap is used to manage
the dynamic memory allocation.

Fig. Q.26.1
Abstract semantic processor 1.12 Case Study: Run Time Structure of C

1.11 Run Time


Structure Important Points to Remember
The run time structure of C makes use of static, stack and heap
Q.27 Explain the run time structure. allocation techniques depending upon the programming entities.
the compiler demands
Ans.:During execution of any program, During the runtime execution of C, the activation record is
block of memory to operating system. This block of memorv maintained.
called run time storage. U There are four methods of parameter passing - 1. Call by value
The run time storage is subdivided Codearea 2. Call by Reference 3. Copy Restore 4. Call by Name
to hold code and data such as Q.28 Consider following C code fragment and represent runtime
i) Code memory for generated Static dataa execution structure for abstract semantic machine.
area
code. void main ()
ii) Data memory which stores data
objects and Stack inta,b;
information
which read_data (a, b) ;
keeps track of procedure
if (a < b)
activations. The data memory is
divided into aa+b ;
else
a) static data area
Heap a a-b
) Stack print(" % d", a);
TOp
c)Heap Fig. Q.27.1 Run time structure
Language Syntax
and Sema
and
Programmlng

1-26 code
without ree. PPL 1-17 Programmimg LanguageSyntax and Semanties
forward
PPL straight for abstract
is a straignllocated for abstract semang. Temporary values
s.
The temporary variables are needed during
code is a allocated

Ans.: The given statically


Q.28.1.
can be following
Fig. the evaluation of expressions. Such variables are stored in the
code
Hence the represented
by
Date memory (D) temporary field of activation record.
It c a n be
machine
Code memory (C)
cell for a 2. Local variables The local data is a data that is local to the
s e t0, reed
cell for b execution of procedure is stored in this field of activation recor
s e t1 , reed
Saved machine registers This field hoids the information
jump 4, D[O]<
D[1 Instrucion regarding the status of machine just before the procedure is called.
pointer
set0,D0-D[1
This field contains the machine registers and program counter
4. Control link This field is optional. It points to the activation
set write,D0
record of the calling procedure. This link is aiso called dynamic
link.
Fig Q.28.1:Execution of code on abstract semantic machine 5. Access link This field is also optional. It refers to the non local

makes use of a d data in other activation record. This field is aiso cailed static link
For stack allocation technique, C program
record. field.
structure popularly known as activation
5. Actual parameters This field holds the information about the
Q.29 Write short note on Activation record.
-

Ans.
actual parameters. These actual parameters are passed to the called

The activation record is a block of


Return value procedure.
used for managing Return values This field is used to store the result of a function
memory Actual parameters
information needed by call.
a single Control link
esecution ofa procedure. (Dynamic link) |2.30 By taking the example of factorial program explain how activation
ecord will look like for every recursive call in ease of factorial (3).
I n C the activation record situated in Access link
is (Static link) ns.
stack area. The contents of
activation Saved machine nain()
record are as shown in status
the
Fig Q.29.1. Local variables
int f;
t factorial (3);
Various fields of
activation record are
Temporaries
as follows Jnt factorial (int n)
Fig. Q.29.1 Model o, if (n=1)
activation record
PPL retum 1;

else (n-1)
PL 1-29 Programming Language Syntax and Semantics
f a c t o r i a l

return (n oncept Activation tree: Activation tree is a data structure used


or specifying the flow of control
among the procedures.
In an
ctivation tree
Step1: main
Each node shows an activation of procedure.
Act
Local ) For showing activation of main
record program root is used.
for main it)If lifetime of 'x' occurs before the lifetime of y then x becomes left
child of y.
Return value To vIf control flows from x then 'x' is parent node of
to y
y'
calling 2.31 Write the output of the
following C program using following8
Act
Act. parameter 3 procedure arameter passing methods.
record )Call by value. i) Call by reference.
for factorial Dynamic link
i) Call by value-result and iv) Call by name.
#include<stdio.h>
int i= 0;
First call intj = 0;

Step 2 void pint x, int y)


Step 3
Act
record for main
main
Local xt=1;
Loca
Act
factorial it=1;
acora record for
factorial (3))
Returm value yt 1;
ord for
acorai
Ream aiue Parametar 3
3 Parameter Dynamicink
Dynamic ink factorial void swap(int x, int y)
Act
accnai record for Retun valus
factorial (2) Parameter13
Retun va
record Dynamic Enk* X=Xty;
Parameter 2
factoria
Dynamic ink y X-y
Act Retum valel
record for
factorial (1)
Parameter XI-y
Second call Uynamic ink

Third call
main)
1-30 Programming Language Syntax
PPL and Sene
{1, 1}; 1-31 Programming Language Syntax and Semantics
inta12 PPL
int b[3 {1, 2, 0} x1,y-0. The x and y values get swapped. But on returning
pali), a[i]); main, the x and y values do not get preserved.
printf"%d, %dn", a[0},
a[1); values. Therefore
The printf statement is for printing b[o] and b[2]
Swapj. a]) we will get 1 2 0.
printf"%d.%d, %dn", bj0], b[1], b[2); Hence output will be
return 0; 1
1 2 0
Ans.: i) Call by value
When Plali], ali] ) is called then
i) Call by reference
In call by reference, the formal parameters get associated with
P(1.1)
actual parameter.
P(x.y) void p(int x, int y)
In the function body P, x and y will be increment. Hence x =
"/
i- 2, y 2. But
x+ 1 x becomes 2, y becomes 2
=
on returning to main, the x and y values will not i+ 1 i = 1/
preserved. y+ 1 y becomes 3 /
printf(" %d %d", a[0], a[1] ) will result as 11
When control returns to main a[0] = x = y =3 and a[1] remains as
When call to swap (j, a[ji] Dgiven it will be
it is i.e. 1.
swap (x, y) After calling swap function the printf statement is printing b[0],
swap (0, 1) b[1] and b[2] i.e. 1, 2, 0.
In the function body of x Hence output will be,
x X+y 3 1
i.e x 0 + 1 =1 1 20
yx-y l) Call by value result
y 1 - 1 =0
xX-Y In call
by value result the actual parameter applied by the caller is
x 1-0 copied into callee's formal parameter the function executes and then
X formal parameter is copied back to caller. No alias or reference is
created between formal and actual parameters. Hence
OECOD Less then
PHOTOcOPY
Less than PHOTOCOPY Price
PPL vntax and Semant
void plint x, int y)

2
{
al0] x, a[0] y Structuring of Data,
i.e.
X+ 1
X1+1=2
Computations and Program
yt 1
i.e. y 1+1 2
2.1 Buit in and Primitlve Types
On returningg to main value of x gets copied to
a[0].. afo. al0] Important Points to Remember
The a[l] remains 1. After swap function tne printr prints
d[u}, b[1]a. Any programming language has
b[2). predefined set of built in
data
Hence output will be, types.
2 1 Programming language support various built in data types such as
1 20
boolean, character, integer and reals.
v) Call by name
Q.1
Explain buit in types of programming languages.
In this method the actual
parameters will be substituted for all Ans.: Any programming language has a predefined set of built in data
occurrences of formal
parameter. tnes This built in data type reflects the behavior of
ypes underiying
Hence hardware.
p( int x, int y) Due to
builtin data type, the values are interpreted differently
plalol, a[1D using hardware instructions.

X+ 1 Following are the types of built in types of programming


i+= 1 Becomes al0=1+1 2 languages.
i+ =0+ 1 =1 1. boolean: This data type define only two values TRUE and
y+1 FALSE. In Boolean algebra the Boolean data type is used.
al1 1+1 2
The basic operations performed are and, not, or.
On returning fromP we get 2,2 as
an output of first 2. character: The
printf prints b[0], b[1] and bl21,printf.
After calling swap, the single character value is represented using
char data type. In C the character type variable is
Hence output will be,
2 2 char choice;

120 3. integers: Integer value can be specified using maximum


and minimum limit. In C there are four types of integer
specifications int, short, long and char
(OGCOnro
END..
Date, Copetaion
4 reas: The real number can be
represented using
exponent model. In C. the floating Strcurimg Dete. Computatioms &Program
represented using float data type. point
num The examples of cartesian product constructors in programming
02 What is primitive dats type languages struetures in C. reeords in Pascal
are
and COBOL
Ans The primitive data pes are elementary data 0.4 What is finite mapping ? Erplain intensionai and ertensional
types
ESw .mepping
mapping.
not buit from some other
types. The values of data typeAns.Finite mapping is a
primitive data function in which domain type is mapped
stomic and cannot be decomposed into simpler to values of range type
constituents
Mary times
the built in data types can be interchangeabh The finite mapping is done using two techniques- intensional and
with buit in data type but there are extensional mapping
exceptions. For example .

mCisapimitive data type which is used to define new constamThe intensional mapping is a routine in which the range type
values are directly associated with domain type values.
22:Data Aggregates and Type Constructors
Finite Mapping

Important Polnts to Remember


Programming languages allows the
objects aggregation of elemente
ro
Intensionai Mapping ExtensioraiMapoing
Ing the object certain constructors are provided. T The extensional
resulting objects are called compound mapping is routine in whicn ra a pe tne

.Forexample - objects. values are associated as data aggregates. For exampie int a(S].
s
similar date type
elements Constructor is aggregation Here integers from subrange 0 to 4 are mapped althougn tnis
which element corresponds to the
declaration does not specity
Q.3 What is Cartesian
constructor? product ? How it is particular subrange.
useful to denote D
Ans.: The cartesian In extensional mapping using indexing technique the elements are
In extensional
product of n sets
A, Aj, A
u*s
AAg Aj, , A, mapped in given subrange. For example
A As is a set whose el
xA, is a set whose elements are denoted
A, denoted ...,

2 where a, belongs to A ordered n-tuples for (i 0;i<s, i )

The caresian a li=i+ 10


product is also used to denote the
For example p type construct@ Elements 10, 11, 12, 13 and 14 are associated with locations a[0],
e constructo,

int int> int al1], a[2]. a[3] and a[4] respectively


Explain the concept ofabstract data type.

DECODE@ Loss than PHOTOCOPY Prise


DECODE@less than PHOTOCcOPY Price
Structuring ons
Data, Coputatlons
&
2.4 ProyN r 2-1 Structurtng of Data, Computations &Program
PPL Let use define some important terminologies that are associated
type is
Ans.:An
abstractdata
objects with type system
1. A set ofdata on those
data objecte
abstract
operations 1. Type: The type can be defined as a specific set of values and
2.A set of the data objects
and operat
eration particular set of operations that can be applied to such values.
of both
manipulate the dat.
3. Encapsulation
3. Er
that user
cannot
2. Object or data object: The data object
such a way
operations
definecd. can be defined as location in memory with
without the use of assigned name. Refer Fig Q.6.1.
of information hiding, Fig. Q.6.1 Data objectx
facility
Encapsulation
provides the
packages and in C++,JAVA, Visual i Basi 3. Type error: The illegal operation that manipulate the data
Examples -In ADA
classes facilitate
data type.
the abstract objects are called type error.
denotes the abstras
ract
in C++ which 4. Type safe or type secure: The operation or a program is said
Following is an example
to be type safe if all the operations in a program are guaranteed
type to always apply to data of the correct ype. Thus in type safe
class student
operations no type error will occur.
private Q.7 Differentiate between static and dynamie type checking
int RollNumber,
Ans.
fioat marks
public: Sr.No. Static Type Checking Dynamic Type Checking
void input_data();
void display_data(); 1. Staticchecking is a kind of | Dynamic checking is a kind
checking which is done at of checking which is done
The operations input_data( and display_data) are
intended compile time. at run time.
manipulate RolINumber and marks data objects. The data obje For example- In C, C++ the For example - In Perl and
and operations are 2.
encapsulated by class. static type checking is Prolog the dynamic type
2.3:Types Systems performed. checking is performed.

Q.6 Explain the concept of 3. The static type checking is The dynamic type checking
type systems.
Ans.: Definition: also called as compile time | is also called as execution
The type system is defined of rules use
as set
the language to structure and time checking.
organize its collection of various typ | checking.
Type systems play
semantics of a languagc.
an
important role in determining
2-6
Structuringof Data, &Progre
Computatons

PPL 2-1 Strueturtngof Data, Camputations &Program


PPL The dynamie
The
chec. PPL
dynamic type checki
detection
of
of For example: Consider a code segment as follows
allows
without
brings flexibility typedef struct Node
errors
programming program design.
program
to this
code. Due int x
running the
can be
detected
erors node;
many node 'first, 'second;
and
reliably
quickly, struct Node "last1, "last2,
automaticaly In the above code the variables first and second are name
time The checking informati
increases the compile similarly variables lastl and last2 are name equivalent. But
t need to be kept maintain.equivalent
overhead. and lastl are not name equivalent as the names for these two
during the execution, Th:irst
causes extra Gto Dype expressions are different. Although all the four variabies first
second,last1,last2 are similar under structural equivalence since they
requirement
duringare representing the same type pointer('struct Node).
execution of program.
Structural Equivalence
Q8 What ib strongtype system? When two expressions are the same basic ype or formed by
Ans.: The strongtype system is a type system that guarantees no
then
to generate type language wth strongtype system 1S saikapplying the same constructor to structurally equivalent types
errors. A
are called structurally equivalent.
to be strongly typed language. A type system is said to be weak ithose expressions
s not strong. Hence a language with weak type system is saidt For example:
be weakly typed language. struct student
There are static type system which
are the strong type systems{
The static type system istype system in which type of ever nt i
a
expression is known at compile time. char name| 10];
Q9 What is type compatibility?
struct employee
Ans.: A strict type system in which one operand with type A
allowed to perform operation with another hint ID;
operand with type B. 1char name|101:
feature is called type compatibility.
Q.10 Explain name and structural student s1;
Ans.: Name Equivalence
equivalence.
employee e1;
If we write
In the name
equivalence the type expressions are given th
names. Hence two type then it is said to be valid, because sl and
el are structurally
expressions are said to be name equivalen
and only if they are identical.
quivalent. Thus sl and el are structurally equivalent.
Structuring of Data,
tations &Prog
Computations

2-8 2-9 Structurtng of Data, Computations&Program


PPL
coercion? one type
rting one type to
to a aubtype NEW_SUBTYPE is NEW_INT range 12..55;
Q.11 What is
convertin
of
process
coercion is the impli convere..
rsions : implicit nversion 2.4: The Type Structure of C++, Java
Ans. Type of
conversions

two types
There are
explicit conversion.
Coercion a.13 Write short note on type structure of C++.
Ans. : The type
structure is divided into two main categories
of C++
- Fundamental types and Derived Types.
Explicit conversion
The fundamental type is integer and float. The integer data type
-

Implicit conversion

Two types ofconversion


is classified into int, char, short, long. The float data type is
Fig.Q.11.1
automatically by the compiler then classified into float and double
conversion is done conversions are also
If the conversion. The
implicit call The derived type of actually derived from the fundamental types-
is called implicit conversion there is
no loss of inform
and pointers
In this type of vice versa
float but not
For example, arrays, class, structure, union, functions
as coercions. converted to
can be
for example integer to float there is no los pointers
conversion from integer
in from float to i C Type structure
means
information but for converting
the information
te
there is a loss.
to be explicit if the programn
The conversion is said Fundamental types Derived ype
one type to another.
specifically writes something converting
for

For example Foat Claes v t Union Pointer


int xyz,p;
integer
p-(loat)xyz;
The identifier xyz is type-caste and this is how explit Cr Shor ngot o
C++
conversion from int to float takes place. Fig. Q.13.1 Type structure of
Q.12 What is subtyping ? elements. For example
but usua Arrays is collection of similar data type
* A
BuDpe 1s a new type based on a parent type
int al10]; I t will create an array
of 10 integer elements
with a more restricted range. It inherits all of the characteristics o create
allows the programmer to
T h e class, structure and union
parent type and in addition, it can be freely intermixed with the par class is well known entity in
C++ by
user defined data types. The
type in calculations and assignment statements. members and member functions
in
which one can encapsulate data
For example -

following code defines the concept of subtyp C++. For example


type NEW_INT is new INTEGER
range 12.55;
type NEW_INT_TYPE is new INTEGER; class stack
subtype SUB_INT is NEW_INT;
Structuring f nutations
Data, Computatio «
2-10 2-11 Structurlng of Data, Computations &Program
PPL of
PPL to represent an expression? Explain it with the help
o16 How
private:
suitable example.

powerful and natural way for representing the


int s/10);
are
Ans.: Expressions
int top
sequence of operations.
public:
void push(int item)
of expression is a tree
The effective way of representation
int pop();
representation.

stack data
structure using class,
class.
creates a For example
class
The above
note on type
structure of Java. 19+(10+3 7)/(20-3*2)
Q.14 Write short in two Consider an expression
classified two categ0
of Java is
structure
Ans. The type will evaluate () first.
2. Derived Types. Step 1:We
1. Built in Data Types * 7=21. Then perform 10 21 31.
Javedat type structure
Step 2:Evaluate 3
** 2=9. Then 20-9 11.
Step 3: Evaluate 3
Buit-in Compoete 31/11 =2.
Step 4:Perform
+2=21.
Floaeng pol Class A T a y e Stpe 5: Perform 19
The tree representation will be

Byte Char Shot Long Float Double

Fig. Q.14.1 Types structure of java


The built in Data Types8:
19
Various data types used in Java are byte, short, int, long, ca
float, double and boolean.
10 20
2.5:Expresslons and Statements
Important Points to Remember of expression
The program is structured
into different units Fig. Q.15.1 Tree representation
for
These units are useful for branching looping andcomputation. Q.16 What is conditional targets?
the conditional
decision mak programming languages support
in programs.
ueeision makAns.
A n s . .SOm
Some
For example in C the tertiary
operator is
There various control structures
are statement using operator.
if a >b
conditional statement. For example
-

used by the used to specify the


switch case, for, if then
else, do while program sucuh
and so gn
Comyutattons.

2-12
Structuringof Data,
written
&Prog PPL 2-13
Structuring of Data, Computations &Program
PPL

otherwise b this
statement
can be
sing
usi.
i) Procedures
ii) Functions
then a a kind
Procedure is ai of routine that does not return
follows- a value. On the
conditional expression as
(a>b)?a.b other hand, functions return a value.
written as ides both procedures and functions. The formal
Pascal provid
In ML it is
a else b
Ifa> b then can be-by value or by reference.
parameters
par

Procedure in Pascal
Example of
P r o c e d u r e
MaxNum (x, y: integer, var z : integer)
Execution and Iteration
2.6:Conditional
begin
if x>ythen
controls.
forms of statement level
Z: X
Q.17 Explain different
controls
forms ofstatement level else
-

Ans.: There are three


execute in the order they apn
1. Composition: The statements end;
on the page.
Example of Function in Pascal
2. Alternation: Two sequences form alternatives. At a time on
Function MaxNum (x, y
: integer): integer; ( returning maximum
one sequence is executed and not both. between two numbers )
3.
3. Iteration: Some set of statements are repeated over and ove var

again.
result integer
begin
if (x > y) then
2.7: Routines
result: =x
else
Important Points to Remember
Routines are collection of statements that are
result:= y:
to be MaxNum: = result;
repeatedly. execute
end
Routines are of two types
Procedures and Functions 2.8:Style Issues:Side Effects and Allasing
-

Using call and return instructions the routines are


handled. .19 Explain the side effects of
non-locals, parameter passing by
a.18 What are reference and of aliasing.
procedures and functions ?
Ans.: Most Ans.Sideeffect of non-locals:
of the programming languages support two types used and each unit has
are
routines 1)If large number of non-locals then program
unrestricted access to these non-locals

(DECADGYa
2-14
Strucmringof Data, utations& Pro
Comwpntao.

PPL read,
understand andmodi
dify. Ther 2-15 Structurtng of Data, Computatlons &Program
becomes
difficult to
might be
modified in
n
chances that the variables onl
nono Thus assignment to one variable affect the value in another
ariable.
environment.

of error
due to unrestricte
unrestrine.

2) Finding
ermors or
cause
use 2.9: Exceptions
non-locals become complex.
reference ImportantPoints to Remember
passing by
S i d e effect of parameter of
Definition of Exception Excenti
Exception: Exception can be defined as an
the actual parameter
might get modis
There are chances that undesirable condition that occurs in the program.
to parameter passing by' reference. Definition of Exception Handling: Exception handling
Side effect of function : As procedures do not return a value, mechanism by which the language can recognize the unexpected
is a
, the
are less side effects of procedures. However, there are seriousSisundesirable and anomalous behavior and specify the response

effects offunction.For example codethat must beexecuted when the exceptionis raised.
Q.20 Explain exception handling mechanism in C++
result: a + fun(a, b) ;
Ans.:C+ exception handling mechanism makes use of three
.In above statement, if function fun uses parameter passing keywords try, catch and throw. The try represents the block of
reference, then fun might produce a change in a or b 1) T statementsin which there are chances of occurring some
reduces the readability of program. exceptional conditions.
2)Another side effect is such statements prevent compileWhen exception detected it is thrown using the throw statement.
from generating optimized code. There exists a block of statements in which the exception thrown is
handled appropriately. This block is called catch block
Side effect Aliasing: The two variables
of are said to be
aliasesi
they share the same data object Following figure illustrates the concept of exception handling
during
unit activation. For exampk
consider following code firagment mechanisms-
mechanisms -

EQUTVALENE (A, B) thraw


A 100 Call to the
function that|
Thus variables A and B are contains
set to
values A and B exception try throws
Now, if we add
B
following statements block excepton
200
WRITE(,)A
The above statement catch
will print 200 block
instead of 100.
Fig. Q.20.1 throw-try-catch mechanism

(DECODE @Less than PHOTOCOPY DECODE@ Less than PHOTOCOPY Price


Price
Strmctringf Data, rions &Prop
Comyutations

PPL

3
2-16

For example Structuring of Program


C++Program
#include <iostreamn>
using namespace std 3.1:Concepts In Support of
void main () Modulartty
try Important Points to Remember
Software module is used in abstraction.
throw 100:
Various functionality that support the concept of
catch (int x) such
such as encapsulation, interfaces, separate
modularity
compilation
cout <<"An exception at "
<< x << endl;
mechanism, creating library of modules and so on.

Q.1 Explain the concept of encapsulation with suitable erample


Ans.
An exception at 100
Output
Definition of Encapsulation : Encapsulation is mechanism by
a
which the program
components can be combined
together to
provide some specific functionality.
END..
Encapsulation supports for information hiding of implementation
of the modules.
In C++, the encapsulation is provided by means of a class. For
instance
class Test

private: Encapsulated data members and


int a,b member functions in a single unit
public: called class.
int add(a,b);

You might also like