You are on page 1of 117
QUESTION BANK Principles of Programming Languages (RCS - 503) B.Tech -CSE (3" Year) Mr. Anuj Khanna (Computer Science & Engineering Department) PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANU] KHANNA(ASST. PROFESSOR) UNIT WISE COURSE CONTENT AS PER AKTU SYLLABUS PRINCIPLES OF PROGRAMMING LANGUAGES (RCS -503) UNIT NO. TOPICS NO. OF QUESTIONS Unit-1 Introduction: Role of Programming Languages: Why Programming Languages, Towards Higher-Level Languages, Programming Paradigms, Programming Environments Language Description: Syntactic Structure, Language Translation Issues: Programming Language Syntax, Stages in Translation, Formal Translation Models 27 Unit-2 Data, Data Types, and Basic Statements : Names, Variables , Binding, Type Checking, Scope, Scope Rules , Lifetime and Garbage Collection, Primitive Data Types, Strings, Array Types, Associative Arrays sRecord Types, Union Types, Pointers and References , Arithmetic Expressions , Overloaded Operators, Type Conversions , Relational and Boolean Expressions, Assignment Statements, Mixed Mode Assignments, Control Structures, Selection Iterations, Branching, Guarded Statements 26 Unit-3 ‘Subprograms and Implementations : Subprograms, Design Issues, Local Referencing, Parameter Passing, Overloaded Methods, Generic Methods, Design Issues for Functions , Semantics of Call and Return, Implementing Simple Subprograms, Stack and Dynamic, Local Variables, Nested Subprograms, Dynamic Scoping. 17 Unit-4 Object-Orientation, Concurrency, and Event Handling : Grouping of Data and Operations — Constructs for Programming Structures, Abstraction Information Hiding, Program Design with Modules, Defined Types, Object Oriented Programming — Concept of Object, Inheritance, Derived Classes and Information Hiding - Templates, Semaphores, Monitors, Message Passing, Threads, Statement Level Concurrency Exception Handling, (Using C++ and Java as Example Language) 23 Unit-5 Functional and Logic Programming Languages = Introduction to Lambda Calculus , Fundamentals of Functional Programming Languages, Programming ML, Introduction to Logic and Logic Programming ~ Programming with Prolog 24 PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANUJ KHANNA(ASST. PROFESSOR) www.uptunotes.com UNIT -1 » Introduction: Role of Programming Languages > Programming Paradigms >» Programming Environments Language Description » Syntactic Structure » Language Translation Issues and Programming Language Syntax > Stages in Translation » Formal Translation Models PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANUJ KHANNA (ASST. PROFESSOR) page 4 www.uptunotes.com Short Answer Type Questions Ques 1. Define the term programming paradigm with example. Ans The word programming paradigm is used in several different, although related meanings in computer science: an example that serves as pattern or model. "A philosophical and theoretical framework of a scientific discipline within which theories, laws, and generalizations and the experiments performed in support of them are formulated". Main programming paradigms are as mentioned below: Imperative Paradigm , Functional Paradigm , Logical Paradigm, Object-Oriented Paradigm. Ques 2. What Are Objectives of Principles of Programming Languages? Ans : Objectives of principles of programming languages are as following: To introduce several different paradigms of programming To gain experience with these paradigms by using example programming languages. To understand concepts of syntax, translation, abstraction, and implementation. To learn new languages more easily and to improve our vocabulary of useful programming constructs, To improve our efficiency and ability to design new algorithms. KES K Ques 3. Explain the concept of orthogonality in programming language design. Ans : The term orthogonality refers to attribute of being able to combine various features of a language in all possible Combinations where each combination must be meaningful. E.g : Suppose a language provides an expression that can provide a value It also provides a conditional statement that evaluates an expression to get a true or false value. Ques 4. What are the general characteristics of a good programming language ? Ans: (i) Clarity , simplicity and preciseness. (i) Orthogonality. (ii) Naturalness for the application. Gv) Support for abstraction. (¥) Portability of the program. ‘Ques 5 Give the full form of BASIC , COBOL , FORTRAN , ALGOL, PROLOG. Ans: BASIC - Beginners All-purpose Symbolic Instruction Code. COBOL - COmmon Business Oriented Language. FORTRAN - FORmula TRANSIation. ALGOL - ALGOrithmic Language. PROLOG - PROgramming in LOGic. Ques 6. What is a compiler? ‘Ans: A compiler is a program that translates the code written in high level language ( Source code) to low level language( machine code) without changing the meaning/semantic of the program. It is also expected that a compiler should make the target code efficient and optimize in terms of time and space complexity. Source code can be programming language, e.g: C , C++, Java, FORTRAN PASCAL etc. Machine code is in the form of binary (0 or 1). PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANUJ KHANNA (ASST. PROFESSOR) page 2 www.uptunotes.com COMPILER Error messages Source code = —) Target machine code Ques 7.Write the regular expression for identifier and whitespace. Ans : Identifier : (letter) (letter/digit)* Whitespace : (delim)+ delim=[“” \t \b] Ques 8. Define formal Language. What are the operations involved in languages? Ans : A language is any countable set of strings over some fixed alphabet, where a string over an alphabet is a finite sequence of symbols drawn from that alphabet. An alphabet or character class is a finite set of symbols. Operations on languages: Following operations are performed in languages : Union, Concatenation, Kleene Closure , Positive closure. Ques 9. Differentiate between Compiler and Interpreter. Ans: SNO COMPILER 1 | Before execution, entire program is scanned by the compiler in one go. 2. _ | List of errors is created by the compiler after the compilation process. INTERPRETER After translating the first line, an interpreter then executes it line by line. ‘An interpreter stops translating after the first error is detected. 3. _| Anindependent executable file is created by the compiler. Interpreter is required by an interpreted program each time. 4.__| The compiler produce object code Interpreter generates byte code. e.g : In Java ‘5. | Compiler is fast and more efficient __| Interpreter is slow and less efficient. 6. | Example : Borland C compiler , Turbo | Example : Lisp interpreter. C++ compiler. Ques 11. Define tokens, Patterns and lexemes. Ans : Tokens: A token is a pair consisting of a token name and an optional attribute value. A token name is an abstract symbol representing a kind of indivisible lexical unit. Example: Keywords, identifiers, constants, operators, punctuations, literals Lexeme: A lexeme is a sequence of characters in the source program that is matched by the pattem for the token, For example in the statement const pi = 3.1416 the substring pi is a lexeme for the token identifier. Patterns: There is a set of strings in the input for which the same token is produced by the output. The set of strings is described by a rule called a pattern associated with a token. Patterns are implemented using regular expressions. PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANUJ KHANNA (ASST. PROFESSOR) page 3 www.uptunotes.com Ques 12. What are the two parts of a compilation? Explain briefly. Ans : Analysis and Synthesis are the two parts of compilation, The analysis part breaks up the source program into constituent pieces and creates an intermediate representation of the source program. Analysis is of following three types: (i) Linear Analysis: Stream of characters are read from left to right and grouped into tokens that have a sequence of characters having a collective meaning. (ii) Hierarchical Analysis: Here the tokens are grouped hierarchically into nested collections with collective meaning. Also termed as Parsing. (iii) Semantic Analysis: Certain checks , like data type compatibility and meanings of statements are ensured by this analysis after parsing is done, so that components of program may fit altogether meaningfully. The synthesis part constructs the desired target program from the intermediate representation, Ques 13. What are the conditions to be satisfied for NFA. Ans: NFA should have one start state. (i) NFA may have one or more accepting states. (ii)Transitions may present on NFA. (iii)There can be more than transitions, on same input symbol from any one state. In NFA, from any state “S” — (There can be at most two transitions. (i) There can be only one transition on real input symbol. (iii)On real input transition it should reach the new state only. Ques 14. Define Backus Naur Form. Ans : Many programming language constructs have an inherently recursive structure to analyse the syntax of statements.BNF is such a formal way to define the programming languages. Example : Definition of an Identifier in BNF : : = | | AD [Cen fz digit = 0) 1]2 | oon. Meta variables or syntactic classes are enclosed within < >. Ques 15. Give the regular expressions for the following langauges = () Set of al strings over alphabet { a, b jconsisting of three consecutive b’s. Gi) Set of all strings containing at least two 0°s over alphabet symbols { 0,1} Ans: @ (a+b)* bbb (a +b)* Gi) (0+1)7000+1)"000+1)* PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANUJ KHANNA (ASST. PROFESSOR) page 4 www.uptunotes.com Ques 16. Differentiate between procedural and object oriented programming. Ans: S.No. | Procedural programming Object oriented programming 1. _ | Programis divided into small parts called | Program is divided into classes and objects. functions 2. __ | Itfollows a top dowa approach of It follows a bottom up approach. development 3. | Importance is given to functions not the data, | Importance is given to data rather than the functions. PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANU] KHANNA (ASST. PROFESSOR) page 5 www.uptunotes.com Long Answer Type Questions Ques 17: Explain the evolution of various programming language paradigm in detail with suitable examples. Ans : Paradigm can also be termed as method to solve some problem or do some task. Programming paradigm is an approach to solve problem using some programming language or also we can say it is a method to solve a problem using tools and techniques that are available to us following some approach. Apart from varieties of programming language there are lots of paradigms to fulfil each and every demand. They are discussed below: Programming Paradigms 1. Imperative programming paradigm = It is one of the oldest programming paradigm. It features close relation relation to machine architecture. It is based on Von Neumann architecture. It works by changing the program state through assignment statements. It performs step by step task by changing state. The main focus is on how to achieve the goal. The paradigm consist of several statements and after execution of all the result is stored. Advantage: 1. Very simple to implement 2. It contains loops, variables etc. Disadvantage: 1. Complex problem cannot be solved 2. Less efficient and less productive 3. Parallel programming is not possible Examples of Imperative programming paradigm: C:: developed by Dennis Ritchie and Ken Thompson Fortan : developed by John Backus for IBM Basic : developed by John G Kemeny and Thomas E Kurtz Imperative programming is divided into three broad categories: Procedural, OOP and parallel processing. These paradigms are as follows: Procedural programming paradigm : This paradigm emphasizes on procedure in terms of under lying machine model. There is no difference in between procedural and imperative approach. It has the ability to reuse the code and it was boon at that time when it was in use because of its reusability. PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANU KHANNA (ASST. PROFESSOR) page § www.uptunotes.com Object oriented programming = The program is written as a collection of classes and object which are meant for communication. The smailest and basic entity is object and all kind of computation is performed on the objects only. More emphasis is on data rather procedure. It can handle almost all kind of real life problems which are today in scenario. Advantages: «Data security + Inheritance + Code reusability Parallel processing approach : Parallel processing is the processing of program instructions by dividing them among multiple processors. A parallel processing system posses many numbers of processor with the objective of running a program in less time by dividing them. This approach seems to be like divide and conquer. Examples are NESL (one of the oldest one) and C/C+ also supports because of some library function. 3. Declarative programming paradigm: It is divided as Logic, Functional, Database. In computer science the declarative programming is a style of building programs that expresses logic of computation without talking about its control flow. It often considers programs as theories of some logic. It may simplify writing parallel programs. Logic programming paradigms (Rule based programming) : It can be termed as abstract model of computation, It would solve logical problems like puzzles, series ete. In logic programming we have a knowledge base which we know before and along with the question and knowledge base which is given to machine, it produces result. In normal programming languages, such concept of knowledge base is not available but while using the concept of artificial intelligence, machine learning we have some models like Perception model which is using the same mechanism. In logical programming the main emphasize is on knowledge base and the problem. The execution of the program is very auch like proof of mathematical statement, e.g., Prolog Functional programming paradigms : The functional programming paradigms has its roots in mathematics and it is language independent. The key principal of this paradigms is the execution of series of mathematical functions. The central model for the abstraction is the function which are meant for some specific computation and not the data structure. Data are loosely coupled to functions. The function hide their implementation. Function can be replaced with their values without changing the meaning of the program. Some of the languages like perl, javascript mostly uses this paradigm, Examples of Functional programming paradigm: JavaScript : developed by Brendan Eich Haskwell : developed by Lennart Augustsson, Dave Barton Scala : developed by Martin Odersky Erlang : developed by Joe Armstrong, Robert Virding isp : developed by John Mccarthy ML : developed by Robin Milner Clojure : developed by Rich Hickey Database/Data driven programming approach — This programming methodology is based on data and its movement. Program statements are defined by data rather than hard-coding a series of steps. A database program is the heart of a business information system, PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANU KHANNA (ASST. PROFESSOR) page 7 www.uptunotes.com and provides file creation, data entry, update, query and reporting functions. There are several programming languages that are developed mostly for database application. For example SQL. It is applied to streams of structured data, for filtering, transforming, aggregating (such as computing statistics), or calling other programs. So it has its own wide application. CREATE DATABASE databaseAddress; CREATE TABLE Addr ( PersonID int, LastName varchar(200), FirstName varchar(200), Address varchar(200), City varehar(200), State varchar(200) ); Ques 18. What is language translator? Explain various translators with example. Also explain the working of a LANGUGE PROCESSOR SYSTEM. Ans : Language Translator : A program that takes as input a program written in one language and produces as output a program in another language. Input program is called source code and output is called target code. We can have translators for following types : (i) One HLL to another HLL.(High Level language). (ii) One FILL to low level language (machine code) ,called compilers. E.g : Java to Byte Code). (iii) Low level to HLL ( These types are called De-Compilers). (iv) One Natural Language translator to another Natural Language translator ( E.g : English to Spanish) (v) Assembly code to machine code( By Assembler). Besides program translation, the translator performs another very important role, the error- detection. Any violation of HLL specification would be detected and reported to the programmers. Important roles of translator are: 1. Translating the HLL program input into an equivalent ML (machine level) program. 2. Providing diagnostic messages wherever the programmer violates specification of the HLL. ‘Skeletal Source Program | Preprocessor __] Source program | Compiter lbs Assembly program Assembler Relocatable Machine Code Loader/inker-editor | «1 ivrary, relocatable obj file Absolute Machine Code PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANUJ KHANNA (ASST. PROFESSOR) page g www.uptunotes.com PREPROCESSOR : A preprocessor produce input to compilers. They may perform the following functions. > Macro processing: A preprocessor may allow a user to define macros that are short hands for longer constructs. > File inclusio ‘A preprocessor may include header files into the program text. > Rational preprocessor: These pre-processors augment older languages with more modern flow-of- control and data structuring facilities. It also provides in built macro facilities of if -else, while constructs if it is not existing in a programming language. > Language Extensions: These preprocessor attempts to add capabilities to the language by certain amounts to build-in macro. COMPILER: Compiler is a translator program that translates a program written in (HILL) the source program. and translate it into an equivalent program in (MLL-binary code), the target program. > An important part of a compiler is error showing to the programmer. > Executing a program written n HLL programming language is basically of two parts: () Source program must first be compiled translated into an object program i) Then the results object program is loaded into a memory for final execution. Source pa oT compe | obj pam bi pem nny Obj pam | opj pgm output ASSEMBLER: Programmers found it difficult to write or read programs in machine language. They use mnemonic (symbols) for each machine instruction, which they would subsequently translate into machine Janguage. Such a mnemonic machine language is now called an assembly language. Programs known as assembler were written to automate the translation of assembly language in to machine language. The input to an assembler program is called source program, the output is a machine language translation (object program), LOADER AND LINK-EDITOR: Once the assembler procedures an object program, that program must be placed into memory and executed. The assembler could place the object program directly in memory and transfer control to it, there by causing the machine language program to be execute. “A loader is a program that places programs into memory and prepares them for execution.” It would be more efficient if subroutines could be translated into object form the louder could “relocate” directly behind the user’s ‘program. The task of adjusting programs to be placed in arbitrary core locations is called relocation. Link editor allows to make a single program from several files of relocatable machine code. These files may have been the result of several compilations, and one or more may be library files of routines provided by the system and available to any program that needs them. Link editors are also helpful in resolving external references , in which code of one file refers to location in another file. This reference may be a data location defined in one file and used in another file PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANU KHANNA (ASST. PROFESSOR) page 9 www.uptunotes.com Ques 19. (i) What is Bootstrapping? How can the cross compilers be generated using this? (ii Let the language L has a subset S , language S has a subset S1 (ie S1 SL) Mention the steps using T-diagrams to generate a cross compiler for L implemented on S , running on machine N where Sis implemented with the help of S1. Any missing data can be assumed by you. Ans : Bootstrapping is a technique to generate new compilers using cross compilers ,which are capable of creating a executable code for a platform other than the one on which the cross compiler runs. Such a tool is required when code compilation is to be performed on a machine that can not be accessed. A simple language is used to translate a more complicated program , which in tum may handle an even more complicated program known as BOOTSTRAPPING. Bootstrapping helps one language to compile itself in its own native language. For bootstrapping , a compiler is characterized by three languages as 1. Source Language (S) : This is compiled by a new compiler. 2. Implementation Language (L) : Used for coding a new compiler. 3. Target Language(T) : Generated by a new compiler ‘Mostly we refer Boot Strapping using T- Diagrams T diagrams were introduced by Bratman in 1961. Other notations are : Cffand $iT Cross compilers are beneficial if: > Target code is not self hosting, ie. ability of a language to compile itself, > Target code is unstable and > Build system is too fast. To develop many embedded systems , cross compilers are only way to develop programs ,if the target hardware does not has resources and capability to compile code itself. E.g : A Microwave Oven has a micro-computer to read its touchpad, door sensor , output to a digital display and speaker, machinery for food cooking. This computer is not powerful enough to mun a compiler , a file system or IDE. Suppose we write a cross compiler for a new language L. in an implementation language Sto generate code for machine N i.e LsN. If an existing compiler for S rans on machine M and generates code for M , i.e. SM, we produce a compiler LywN i.¢.a compiler from L to N that runs on M. Here LyN is a produced cross compiler after bootstrapping. PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANU] KHANNA (ASST. PROFESSOR) page 10 www.uptunotes.com (i Solution of given problem is as below : Lt we done a Compiler Sta wisps Te pemwate Soh 5 nodive Compiler for 5 ze SA Si A\A A Apr: To qennole Le Nim el Lam dx a Chord Compiler} al a] Iss AJA] LAJ nore: Sue Yo Code for Sk mle A amd L do inplmeated on S 5 2 eR. Le a toca denplementecl om motrine . Ques 20. Discuss the action taken by every phase of the compiler on string a= (a++ + ++b) * ¢/ 6. Ans : (i) Lexical Analyzer: Tokens: idl = (id2+++++id3) * id4 /6. (ii) Syntax Analyzer : PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANUJ KHANNA (ASST. PROFESSOR) page 44 www.uptunotes.com (ii) Semantic Analyzer a amd b OM D pan (4 Lot), tree Tyre Crhng Ja dwt (iv) Intermediate Code Generation (¥) Machine independent code optimiz: Temp1=id3 +1 or Temp! = ++id3) Temp! + +4id3 Temp2=id2 +Temp1 Temp2=Templ * id4 Temp3 = Temp? * id4 id1= Temp2/6.0 (vi) Code Generation Temp4—Temp3/6.0 idl-Temp4 LOAD id3,R1 ** Temp are temporary variables INC RI LOAD id2 , R2 ADD RI — RI ,R2 LOAD id4 , R3 MUL RI RI, R3 DIV R1, 6.0 STORE id1, RI Ques 21: Explain the following terms w.r-t programming languages: (@Data Abstraction (ji) Information Hiding (iii) Portability (iv) Clarity and naturalness. Ans : Data Abstraction : Data abstraction is the reduction of a particular body of data to a simplified representation of the whole. Data abstraction refers to providing only essential information to the outside world and hiding their background details, i.e., to represent the needed information in program without presenting the details. Data abstraction is a programming (and design) technique that relies on the separation of interface and implementation. Let's take one real life example of a TV, which you can turn on and off, change the channel, adjust the volume, and add external components such as speakers, VCRs, and DVD players, BUT you do not know its intemal details, that is, you do not know how it receives signals over the air or through a cable, how it translates them, and finally displays them on the screen, Information Hiding : It is the principle of segregation of the design decisions in a computer program that are most likely to change, thus protecting other parts of the program from extensive PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANU] KHANNA (ASST. PROFESSOR) page 12 www.uptunotes.com modification if the design decision is changed. The protection involves providing a stable interface which protects the remainder of the program from the implementation (the details that are most likely to change). Written another way, information hiding is the ability to prevent certain aspects of a class or software component from being accessible to its clients, using either programming language features (like private variables) or an explicit exporting policy. Portability: In high-level computer programming is the usability of the same software in different environments. The pre-requirement for portability is the generalized abstraction between the application logic and system interfaces. When software with the same functionality is produced for several computing platforms, Clarity and Naturalness: A language needs a syntax that, when properly used allows the program structure to reflect the underlying logical structure of the algorithm. Possibly a program design should be translated directly into proper programming statements that reflect the structure of the algorithm. Sequential algorithms, concurrent algorithms, logic algorithms etc have different natural structures that are Represented by programs in those languages. -cture and Virtual Ques 22. Illustrate the term Virtual in computer terms. What is Virtual Arcl Computers, explain with hierarchies of virtual machines. Ans : One of the classic developments in computing systems is virtual memory, a combination of hardware and software that creates the illusion of private memory for each process. In the same school of thought, a virtual network interface protected across process boundaries could be accessed at the user level. With this technology, the "consumer" manages its own buffers and communication schedule while the "provider" handles the protection. Virtual architecture is a way to implement Virtual computers or machines. Generally computer can be constructed using any one of the following four techniques: () Hardware realization: Representing the data structures and algorithms directly with physical devices. (i) Firmware realization: Representing the data structures and algorithms by micro programming a suitable hardware computer. (ii) Virtual Machine : Representing the data structures and algorithms by programs and data structures in some other programming language. (i) Through some combination of these techniques representing various parts of the computer directly in hardware, in microprograms, or by software simulation. If programming languages are defined in terms of their virtual computers so that each language is associated with a single commonly understood virtual computer. Since languages are normally defined by giving the semantics for each construct individually, therefore language definitions have implicit underlying virtual computer. Two different implementations of the same language may utilize a different set of data structures and operations in the implementation. Example : Ifa virtual computer contains both an integer addition operation and a square root operation, the implementor may choose to represent the integer addition operation provided directly by underlying hardware, whereas the square root may be represented by a software simulation as a procedure. PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANU] KHANNA (ASST. PROFESSOR) page 13 www.uptunotes.com Three factors that lead to differences among implementations of the same language = (@ Differences in each implementer’s conception of the virtual computer that is implicit in the language definition. (i) Differences in the facilities provided by the host computer on which the language is to be implemented. (ii) Differences in the choices made by each implementer as to how to simulate the virtual computer elements using the facilities provided by the underlying computer and how to construct the translator so as to support virtual computer’s specifications. Layers and Hierarchy of Virtual Computers for a Web Application 1/P Data Web Application Computer (As HTML pages implementation) 0/P results Web Virtual Computer (Browser code in C or Java) C Virtual Computer (Implemented by run time library routines loaded with, compiled program) (Operating System jual Computer (Machine code implementation executable on firmware) Firmware ual Computer (Machine code instructions by microcode executed on actual computer) Actual Hardware Computer (Implemented by physical devices) PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANU] KHANNA (ASST. PROFESSOR) page 14 www.uptunotes.com Ques 23. Briefly explain how software simulation is done with an example. Compare it with language translation: Aas : Software Simulation: Running programs through another host computer, a computer whose machine language is the high level language. 1. Here direct translation of a program in high level language to machine language is not performed. 2. Construction of a set of programs in the machine language of the host computer that represents the Algorithm and data structures necessary for execution pf programs in the high level language. So we design a software running on host computer (a high level language computer)which otherwise have to be designed in hardware. This is known as Software simulation/ Interpretation Difference between a translation and simulation is that translator simple produces an equivalent program in its object language, which in turn can be executed by an interpreter for the object language Y Simulator executes the input program directly. A language is implemented on a computer by a combination of translation and simulation. Y A program is firstly translated to an executable form. This is done by several independent Piece of codes written in procedures, routines. Y These separate pieces are combined during the loading phase with a set of run time support Routines that represent software simulated operations into an executable form of the program, which is decoded and executed by the simulation. Tyree Language Taruemewrarion Row Te soPre kT UBRARY| a ) Ginmdocion Pours oe The major disadvantage of translation is the loss of information about the program. If the data from the source program are translated to a sequence of machine language addresses and there is an error in the program, then it is often difficult to determine which source language was executing and which data objects were being manipulated. With simulation all of this information is still available to display for the user PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANU] KHANNA (ASST. PROFESSOR) page 15 www.uptunotes.com Ques 24. Write Short notes on the following: (H Classes of binding times (ii) Programming Environments Ans : At the very basic, binding is assigning one thing to another, usually, values to variables either by explicit declaration or implicit declaration or binding a program element to a particular property/attribute from the given set of possible choices. Adributes can be data type , value , scope , storage class etc. The time during program formulation or processing when this choice is made is termed as the binding time ofthat property for that element, 1, Execution Time Binding(Run time binding or late binding): This includes binding of variables to their values at run time , binding with storage locations. These are of following two types, (a) On entry to a subprogram or a block: In C and C+ , the binding of formal parameters to actual ones to a particular storage locations may occur only on the entry to a subprogram. ** Block is the set of statements within curly braces { }. (b) At arbitrary points during execution: Some bindings may occur at nay point during execution of a program. The most important example here is the basic binding of variables to values through assignment, whereas some languages like LISP, Smalltalk and ML permit the binding of names to storage locations at arbitrary point. 2. Translation Time Binding( Compile time or early binding): These are of following three types (a) Bindings chosen by the programmer: While coding a programmer makes several decisions to select proper variable names , data types of variables , scope, data structures ete.which represent compile time binding. (b) Bindings chosen by the translator: Bindings selected by the translator without any programmer intervention. .g: The relative location of a data object in the storage allocated for a procedure is generally handled without knowledge of programmer. Array storage and their descriptors is also the example of thgis type (c) Binding chosen by the loader: Translator binds variables to addresses within the storage designated for each subprogram. This storage must be allocated actual addresses within the physical computer that will execute the program. This occurs during load time or link time. 3. Language Implementation Time: Some aspects of a language may be the same for all programs that are run using particular implementation of a language but they may vary b/w implementations.E.g: the details of arithmetic operations depend on hardware. 4. Language Definition Time: Most of the structure of a programming language is fixed at the time the language is defined w.r.t specifications of various alternatives available. E.g: various statement forms like If-else, nested if-else, switch case, array , pointers are often fixed at definition time. Example : In the assignment statement X = X+10 various binding times may occur as below: > Set of types for variable X (float, int, Boolean) which is fixed at compile time, > Types of variable X fixed at translation time. > Set of possible values of X. PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANU] KHANNA (ASST. PROFESSOR) page 16 www.uptunotes.com > Values of variable X at different points of program may change. New value will depend on the previous value of X. > Representations of constant 10. > Properties of operator + Ques 25. What do you understand by operating and programming environment? List various attributes of a good operating and programming environment. Ans : Incomputer software, an operating environment or integrated applications environment is the environment in which users run application software. The environment consists of a user interface provided by an applications manager and usually an application programming interface (API) to the applications manager. An operating environment is usually nof a full operating system, but is a form of middleware that rests between the OS and the application. For example, the first version of Microsoft Windows, Windows 1.0, was not a full operating system, but a GUI laid over DOS albeit with an API of its own. Similarly, the IBM U2 system operates on both Unix/Linux and Windows NT. Usually the user interface is text- based or graphical, rather than a command-line interface (¢.g., DOS or the Unix shell), which is often the interface of the underlying operating system, In the mid 1980s, text-based and graphical user interface operating environments surrounded DOS operating systems with a shell that turned the user's display into a menu-oriented "desktop" for selecting and running PC applications. These operating environment systems gave users much of the convenience of integrated software without locking them into a single package. r Programming Environment ‘A programming environment in which a program is created and tested. It consists of a set of tools and a command language for invoking them. Typical tools are editors, debugger, verifiers and test data generators, Some used programming environments are as described below: (A). Batch Processing Environment : A batch system has similar jobs in nature grouped together with the instructions necessary to allow them to be processed without intervention. The monitor is a system software responsible for interpreting and carrying out the instructions in the batch jobs. Advantages: Move much of the work of the operator to the computer... Increased performance since it was possible for job to start as soon as the previous job finished. Disadvantages: > Tumaround time can be large from user stand point. > More difficult to debug program. > A job can corrupt the monitor thus pending jobs > A job could enter an infinite loop. PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANU] KHANNA (ASST. PROFESSOR) page 17 www.uptunotes.com (B) Multiprogramming Systems: In this type of environment several jobs are loaded into the memory at once and cycle throng them in some order and working on each of them for a specified periodor switching of time (©)Time Sharing Environment: In this type OS is responsible for switching between the jobs known as processes. Each used terminal is associated with one or more jobs on the computer. During context switches the user has an impression that she or he has direct access to the system. Interactive processes are given a higher priority so that when /O is requested the associated process is quickly given control of the CPU so that it may process it (D) Multiprocessing Environment: Here more than one CPU combined with each other, work for parallel processing and very fast execution of programs. ) Distributed & Network Environment: Here systems that are transparent to each other, with redundant resources and a sharing of the workload among the different computers. ©) Networking Environment: Multiple computers are interconnected with each other under networking protocols and topologies having common OS and shared resources. (G) Embedded Environment: This has a special purpose dedicated computer programs which can perform few complex and limited tasks only. Usually programmed at chip level , microprogrammed units with Assembly Code implementation. Example: Washing Machines, Microwave oven , traffic light and signals, factory controllers. (H) Real time Environment: RTOS is an OS that guarantees to complete a task within a given time constraints. Hard real time and soft real time systems. This type of environment is multitasking , process threads that can be prioritized, sufficient number of interrupt levels. Ques 26. Explain general syntactic criteria of a programming language? Also illustrate syntactic elements of a language. Ans : The primary purpose of syntax is to provide a notation for communication between the programmer and the programming language processor. Details of syntax are chosen on the basis of readability which is unrelated to primary goal of communicating information to the language processor. The general goals for syntactic criteria are of making programs easy to read write translate and unambiguous. Readability: A program is readable if the algorithm and data structure represented are easily inspected by reading the text. This is called self-documenting program. Readability is enhanced by using proper structured statements, indentations, keywords, noise words, comments. Greater is the variety of syntactic constructs used, the more easily the program structure may be made to reflect different underlying semantic strmctures. ‘Writability: Syntactic structures that make program easy to write are generally in conflict with those which are easy to read. Use of regular and concise structure make program more writable. Implicit syntactic conventions that allow declarations and operations to be left unspecified make programs shorter and easier to write but tough to read. Redundancy makes program harder to write PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANU] KHANNA (ASST. PROFESSOR) page 1g www.uptunotes.com verifiable or can be corrected with less Ease of verifiabi effort. But to make overall correct program is too tedious task. : Making the correct program which is easi Ease of translation: Making the program easily to be translated into object code / executable code. This is completely dependent on the attributes and type of translator software. The Lisp is a language which neither easily readable nor writable but extremely simple to translate. Programs become harder to translate when complexity of syntactic constructs increases as in C C++ Java, COBOL. Lack of ambiguity: An ambiguous construct allows two or more different interpretations. Generally every language construct has a unique meaning in itself. Ambiguity occurs not in the structure of individual program elements but in the interplay b/w different structures. Various Syntactic Elements of any programming language are as described belo > Character Set : Widely used character sets are ASCII(American Standard Code for Information Interchange) which contains special characters, operators, digits, letters > Identifiers: These are user defined names given by the programmers to variables, functions, arrays , pointers etc...A string of letters and digits beginning with a letter. In C a special character underscore can be used as separator b/w two distinct identifier names. > Operators: Several programming constructs have some variations in operator symbols. Unary , binary and temary operators are the basic categories-E.g : +, - Hy /s, &8,-, 2, Fete. > Keywords: Those names which are fixed in their meanings and can not be used as an identifier. Their definitions are reserved in language library. E.g : int , real, float , char , printf, puts, getch, if-else, while, do , return, malloc , new , class , private , public , protected etc. » Noise words: These are optional words inserted in between the program statements to improve the readability. Like in COBOL , goto statement may have an optional TO .So we may write only GO Label instead of GOTO label. > Comments: Inclusion of comments make program well documented. Important Sections of programs % orl. can be indicated by writing comments before it. E.g.in C we use % ... Lin FORTRAN, // in C++ and Java. Single % in Prolog. > Blanks/Spaces: Rules of use of blanks vary from language to language.In C language x+4(No blank) and x+ +( with a blank) has a significant difference. > Delimeters: This marks the begin and end of some program unit like loop, functions etc. Pair of curly braces { }. Begin ......end statements which form a block or subprogram are called delimeters. > Free and fixed field formats: A syntax is free field if program statements may be written anywhere on an input line without regard for positioning on the line or for breaks between lines. Exg: C, C+, Java, Prolog, ML and most of the modern languages are free field. A fived field syntax utilizes the positioning on an input line to convey information. This is mostly seen in assembly language. PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANU] KHANNA (ASST. PROFESSOR) page 19 www.uptunotes.com ** Fived field syntax is now obsolete and rarely used in language implementations. > Expressions: Expressions are functions that access data objects in a program and return some value, These are basic building blocks from which program statements are developed. Eg :xt4*y%3, if(>=3),a==b,a&& bete. > Statement : These are most prominent syntactic components in imperative languages. Statements can be simple, compound and complex. Ques. 27 (i) What do you mean by formal translation model? Explain BNF and EBNI (ii)What are parse trees? Explain Chomsky Hierarchy. Ans : Formal translation models for any programming language generally refers to the grammar defined for syntax specification. This is based on mathematical foundation of formal theory of programming languages. A formal grammar is just a grammar specified using a strictly defined notation. The two classes of grammars useful in compiler technology include the BNF grammar (Backus Naur Form) and regular grammars. Various Translation models are as : ¥ Backus Naur Form Extended BNF Parse Trees Regular grammars and Regular Expressions Fin State Automata. Y Push Down Automata. 1. Many programming language constructs have an inherently recursive structure to analyse the syntax of statements. BNF is such a formal way to define the programming languages. Example : Definition of an Identifier in BNF : : = | < id> | < letter> = a|b|e...-y |Z :=0|1/2| 9 Meta variables or syntactic classes are enclosed within < >. Extended Backus-Naur form (EBNF) is a collection of extensions to Backus-Naur form, Not all of these are strictly a superset, as some change the nule-definition relation ::= to =, while others remove the angled brackets from non-terminals. More important than the minor syntactic differences between the forms of EBNF are the additional operations it allows in expansions. For example, the rule: ::=[ "-" ] allows factors to be negated. Repetition : In EBNF, curly braces indicate that the expression may be repeated zero or more times. For example, the rule: == { "," } defines a conventional comma-separated argument list Grouping :To indicate precedence, EBNF grammars may use parentheses, (), to explictly define the order of expansion. For example, the rule: ::= ("+" | "-") defines an expression form that allows both addition and subtraction. 3. Regular extensions to BNF: PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANU] KHANNA (ASST. PROFESSOR) page 20 www.uptunotes.com It’s common to find regular-expression-like operations inside grammars. For instance, the Python lexical specification uses them. In these grammars: + postfix * means "repeated 0 or more times” + postfix + means "repeated 1 or more times" + postfix ? means "0 or 1 times" The definition of floating point literals in Python is a good example of combining several notations: floatnumber ::= pointfloat | exponentfloat pointfloat ::= [intpart] fraction | intpart "."" exponentfloat ::= (intpart | pointfloat) exponent intpart = fraction 1 digit exponent Cre" | MEN) [4" [9] digite It does not use angle brackets around names (like many EBNF notation , yet does use ::= (like BNF). It mixes regular operations like + for non-empty repetition with EBNF conventions like [ ] for option. Ans :(ji) Parse Trees: Parse tree is the graphical representation of symbol. The symbol can be terminal or non-terminal. ¥ In parsing, the string is derived using the start symbol. The root of the parse tree is that start symbol. Y Itis the graphical representation of symbol that can be terminals or non-terminals. "Parse tree follows the precedence of operators. The deepest sub-tree traversed first. So, the operator in the parent node has less precedence over the operator in the sub-tree Leaves: labeled by a terminal or «. Interior nodes: labeted by a variable. Children are labeled by the right side of a production for the parent. Root: must be labeled by the star Let productions are: S > T+T|T*T,S—a|b|c and input string is a *b +c then parsing steps JN a are: s PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANUJ KHANNA (ASST. PROFESSOR) page 24 www.uptunotes.com /N, a a b o Chomsky Hierarchy: According to Chomsky hierarchy, grammars are divided of 4 types: Type 0 : known as unrestricted grammar. Type 1 : known as context sensitive grammar. Type 2 : known as context fiee grammar, Type 3 : Regular Grammar. ‘Type 0: Unrestricted Grammar: These grammars include all formal grammars. Type 0 grammar language are recognized by turing machine. These languages are also known as the Recursively Enumerable languages. Grammar Production in the form of o> f, where ais (V+ T)* V(V+T)* V: Variables , T : Terminals. fis (V +T)* In type 0 there must be at least one variable on Left side of production. For example, Sab > ba, AS. Here, Variables are S, A and Terminals a, b. Unristricted Grammar (Recognized by Turing Machine) Context Sesitive ‘Grammar (Accepted by Linear Bound Automata) * Context Free Grammar (Accepted by Push ‘Down Automata) Regular Grammar (Acceped By Finite Automata) PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANU] KHANNA (ASST. PROFESSOR) page 22 www.uptunotes.com Type 1: Context Sensitive Grammar: Type-1 grammars generate the context-sensitive languages. The language generated by the grammar are recognized by the Linear Bound Automata, In Type 1, First of all Type 1 grammar should be Type 0 and Grammar Production in the form of a + f.. For Example ,S > AB, AB — abc , B > b. Length of a must be less than or equal to than of 2. Type 2: Context Free Grammar :The language generated by the grammar is recognized by a Pushdown automata, Type-2 grammars generate the context-free languages. In Type 2: First of all it should be Type 1.and Left hand side of production can have only one variable. |= 1 and no restriction on f. For example, S > AB, A> a,B—> Db Type 3: Regular grammar: These languages are exactly all languages that can be accepted by a finite state automaton.Type 3 is most restricted form of grammar. Type 3 should be in the given form only V > VI*/ Te. (or) V+ T*V /T* for example : S > ab PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANU] KHANNA (ASST. PROFESSOR) page 23 www.uptunotes.com UNIT -2 Data, Data Types and Basic Statements » Names, Variables , Binding Vv Type Checking Primitive Data Types, Strings Vv Array Types, Associative Arrays v Record Types, Union Types Pointers and References Vv Arithmetic Expressions Type Conversions Vv Relational and Boolean Expressions Assignment Statements Vv Mixed Mode Assignments Vv Control Structures: Selection ,Iterations, Branching » Guarded Statements PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANU] KHANNA (ASST. PROFESSOR) page 24 www.uptunotes.com Short Answer Type Questions Ques 1. What are Floating-point literals? ‘Ans : The floating point literals can be laid out in either the decimal device as in 1.568 within the decimal system, an exponent can be represented by way of adding the character e or E and more than a few after that, as an example, 2.3e4 means "2.3 instances 10 to the power of 4". A + individual may be targeted before the cost ofthe exponent, but ithas no impact, for example 2.3e4 and 2.3¢ + 4 are the same. The - character added before the price ofthe exponent changes the meaning to be "divided by 10 to the power of". For example, 2.32-2 means "2.3 divided by 10 to the power of 2". or 2.3 x 10-2. Ques 2. What is explicit type casting? ‘Ans : This process is user defined. Here the user can type cast the result to make it of a particular data type. Generally Lower data type is converted into higher one (e.g : int to float, float to double, short int to long Int. In C : (data type) variable, In C++: data type( variable). In Java : Narrowing or Explicit Conversion If we want to assign a value of larger data type to a smaller data type we perform explicit type casting or narrowing. This is useful for incompatible data types where automatic conversion cannot be done. Here, target-type specifies the desired type to convert the specified value to. Ques 3. Differentiate between primitive data types and user defined data types. Ans: Primitive or Fundamental data types are basic built-in data types of C programming language. There are three fundamental data types in C programming. They are an integer data type, floating data type and character data type. Those data types which are defined by the user as per his/her will are called user-defined data types Examples of such data types are structure, union and enumeration, Ques 4. What is scope and life time of variables? Ans : The scope of a declaration is the part of the program for which the declaration is in effect. The lifetime of a variable or object is the time period in which the variable/object has valid memory. Lifetime is also called "allocation method" or "storage duration.” C/C++ use lexical scoping. Lypss of Life thine, Static: A static variable is stored in the data segment of the "object file” ofa program. Its Lifetime is the entire duration of the program's execution. Automatic: An automatic variable has a lifetime that begins when program execution enters the function or statement block or compound and ends when execution leaves the block. Automatic variables are stored in a "function call stack" Dynamic: The lifetime of a dynamic object begins when memory is allocated for the object (e.g., by a call to malloc() or using new) and ends when memory is deallocated (e.g., by a call to free() or using delete). Dynamic objects are stored in "the heap". Ques 5. What are records? Ans : A record is a data structure that groups together related items of data. These are slightly more complex than arrays as you can store more than one type of data together. For example, with a game, it could be useful to set up a data structure which collects a player's login and their score in one structure. Creating records will vary in different languages. Python uses a data structure called ‘dictionaries’ that has some features of the record structure. In C and C++ it is implemented by structures (keyword struct). PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANU] KHANNA (ASST. PROFESSOR) page 25 www.uptunotes.com Pascal arrays allow you to define type of variables that can hold several data items of the same kind but a record is another user-defined data type available in Pascal which allows you to combine data items of different kinds. Records consist of different fields. Suppose you want to keep track of your books in a library, you might want to track the following attributes about each book — Title , Author , Subject Book ID Defining a Record To define a record type, you may use the type declaration statement. The record type is defined as — a Here is the way you would declare the Book record field-1: field-typet; type field-2: fleld-type2; a title: packed array [1..50] of char; author: packed array [1..50] of char; subject: packed array [1.-100] of char; book_id: integer; end; field-n: field-typen; ‘The record variables are defined in the usual way as Ques 5: What are mixed mode arithmetic expressions? Ans : Ina statement or expression if one the operand is real (float) and another one is integer then expression is called as Mixed Mode Arithmetic Expression. If in an expression either operand is of real then output is always in real format. If both operands are real then output will be in real formats. Rules for Evaluation Mixed Mode Arithmetic Expression Rule 1 : Evaluate Expressions always from Left to Right Rule 2 : Priority of an operator is also considered while calculating an expression . Operator Priori Descending order Rule 3: If the operands of this operator are of the same type means either Integer or Real, compute the same for result in that operator only. Rule 4 :If one of the operator is Integer and other one is real then convert integer number to real number and ‘compute the result in real number only. sin PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANU] KHANNA (ASST. PROFESSOR) page 26 www.uptunotes.com Ques 6. Differentiate between structures and unions. Ans STRUCTURE UNION Keyword | Thekeywordstructis usedto define a structure The keyword union is usedto define a union sie | Whenavariableisassociatedwita stucture,the when variableis associated wih a union, the compier compiler alocatesthememoryforeachmerber.The | allocates te memay by considetngthe size of the size fstrucueis greaterthan or equal tothe sumof | largest memay, So, sizeof union is equal to the size sizes ofits members. oflargestmember, Memory | Eachmember within structure's assigned unique Memory allocatedis shared by individual members of storage areaof location union Value | Alteingthevalue of amemberwillnotaffedother ‘Altering the value of any ofthe member willater other Altering | members ofthe stucture. membervalues Accessing Accessing | indidualmerber canbe accessedatatime Only one member can be accessed atatime, [mene Several members of a structure canintialZz@ at once. Onl the rst member of a union canbe initialized. Ques 7. Discuss about Abstract Data Types with appropriate examples. Ans : An abstract data type, sometimes abbreviated ADT, is a logical description of how we view the data and the operations that are allowed without regard 18 how they will be implemented. ADT may be defined as a "class of objects whose logical behaviout is defined bya set of values and a set of operations". ADTs are a theoretical concept in computer science, used itt the design and analysis of algorithms, data structures, and software systems, and do not correspond to specific features of computer languages—mainstream computer languages do not directly support formally specified ADTs. An ADT consists not only of operations, but also of values of the underlying data and of constraints on the operations. For example, an abstract stack, which is a last-in-first-out structure, could be defined by three operations: push, that inserts a data item onto the stack; pop, that removes a data item from it; and peek or top, that accesses a data item on top of the stack without removal. Ques 8. Explain the following terms with three examples for each = @) Programmer defined data objects (b) System defined data object. > Ans : (a) Programmer defined data objects: Those data objects which are designed by the programmers and defined during program development are called programmer defined data objects. Eg: Identifiers , array , structures , enum , union, class. These can be explicitly created and manipulated by the declarations and other statements in code. (b) System Defined data objects are set up by virtual computer to maintain the language library symbol table management during program execution and are not directly accessible to the programmer. E.g: Run time storage stack, heap storage, System FILES and buffers, activation records, records , free space lists PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANU] KHANNA (ASST. PROFESSOR) page 27 www.uptunotes.com Ques 9. Differentiate b/w structure and a class. Aas : A structure is a collection of variables of different data types under a single unit. It is almost similar to a class because both are user-defined data types and both hold a bunch of different data types. ‘A dlass is a user-defined blueprint or prototype from which objects are created, Basically, a class combines the fields and methods (member function which defines actions) into a single unit. S.NO Class Structure 1. | A class is a reference type. When an object of the | A struct is a value type. When a struct is class is created, the variable to which the object is | created, the variable to which the struct is assigned holds only a reference to that memory. _ | assigned holds the structs actual data. 2. | Changes made through one variable are reflected | The new variable and the original variable in the other variable because they both refer to the | therefore contain two separate copies of the same data. same data. Changes made to one copy do not affect the other copy 3._| Class are reference type so they are stored as| Structures are stored as a stack on heap on memory. memory. 4,_| Members of a class are private by default Members of struct are public by default. 3._[ A class can be abstract A structure can't be abstract, 6 | Aas contains data member and member ‘A structure contains ouly data member. function. 7._| Classes can be inherited Structures can not be inherited. 8._| A class can have a volatile field The structure can't contain a volatile field 9, | Ficldsare automatically initialized with | No such initialization in structures. classes to 0/false/null Ques 10, What is l-value and r-value in assignment statements? Ans : L-value: “I-value” refers to memory location which identifies an object. L-value may appear as either left hand or right hand side of an assignment operator(=). I-value often represents as identifier. R-value is the value to be evaluated at right side of assignment statement. E.g:a-2,a-b,a-b+5S-w,a=b+++~b. Steps for computation of assignment statements are = Y Compute the I-value of the first operand expression. Y Compute the r-value of the second operand expression. ¥ Assign the computed r-valne to the computed I-value data object Y Return the computed r-value as the result of the operation, v Ques 11. Define pointers and its operators. Aas : A pointer is a variable whose value is the address of another variable, i.e, direct address of the memory location. Like any variable or constant, you must declare a pointer before using it to store any variable address. The general form of a pointer variable declaration is Data type *var-name; Here, data type is the pointer's base type; it must be a valid C data type and var-name is the name of the pointer variable. The asterisk * used to declare a pointer is the same asterisk used for multiplication. PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANU] KHANNA (ASST. PROFESSOR) page 28 www.uptunotes.com However, in this statement the asterisk is being used to designate a variable as a pointer. Valid pointer declarations int “ip; /* pointer to an integer “/ double “dp; /* pointer to a double */ float “fp; /* pointer to a float */ char “ch / pointer to a character */ Initialization: data type * ptr_var = & var name 2 ; &(ampersand) is known as address of operator and *(pointer) is called value at address or indirection operator Long Answer T uestions Ques12. What is a type system? Explain properties of types and objects. What is EDT and how are data types specified, explain with an example? Ans : Type theory deals with classifying entities into sets called types. A type is a category of entities. A type system is a tractable syntactic method for proving the absence of certain program behaviours by classifying phrases according to the kinds of values that compute. Use fullness of Types: Error detection, Safety, Design, Abstraction, Software Evolution, and Documentation. Elementary data types (EDT) : These are also called primitive data types like integer ,float , char ete Properties of EDT and Objects: Data objects are run time grouping of one or more pieces of data in a virtual computer. These are mainly of two kinds; Programmer defined and System defined. > Programmer Defined data objects exist during the execution of program like variables, constants, arrays, files etc.These can be explicitly created and manipulated by the declarations and other statements in code. > System Defined data objects are set up by virtual computer to maintain the language library , symbol table management during program execution and are not directly accessible to the programmer. E.g: Run time storage stack, heap storage, System FILES and buffers, activation records, records , free space lists. > Data object represents a container for data values for storage and retrieval of data. > Data value can be a number, character, string , pointer stored in a bit pattern in memory block. Data objecta Bit pattern 1001 of P=7 ,at address 2006 location in computer memory with name Pp Address 2006 PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANU] KHANNA (ASST. PROFESSOR) page 29 www.uptunotes.com > Data objects participate in various bindings during life time .Auributes of objects are invariant during its life time, but bindings may change dynamically. Some important attributes and bindings are as mentioned below: (i) Typer int, float , long int . char ,double etc. (ii) Location or memory (ii) Value contained in memory block. (iv) Name of the memory block. (») Component: The binding of a data object to one or more data objects of which it is a component is often represented by a pointer value and it may be modified by a change in the pointer. Elementary data object contains a single data value. A class of such data objects over which various operations are defined is known as EDT (Elementary data type)..¢ : integer , real , character, Boolean enum union, pointers. Specifications of EDT are as follows: (i) Attributes: Basic attributes of any data object such as data type and name are usually invariant during life time of data object. Some attributes may be stored in a descriptor called as Dope ‘Vector and other may be used as storage representation of data objects. (i) Values: The type of a data object determines the set of possible values it may contain. E.g An integer array holds the set of integer values only (ii) Operations: The set of operations defined for a data type determine how data objects of that type may be manipulated. Operations may be primitive, that are specified as a part of language definition Programmer defined operations like subprograms, methods as a part of class definitions. Operation is a mathematical function for a given input arguments called range which generate A result in the form of output set called domain. Signature of an operation signifies a number , order and data types of the arguments in the domain of an operation. op name : arg type x arg type x arg type x rg btype — result type Ques13 . What is enumerated data type? Explain properties of enumeration with suitable examples. Ans : Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names to integral constants, the names make a program easy to read and maintain. It has an ordered list of distinct values. Programmer defines both the literal names to be used for the values and their ordering using a declaration like in C. enum student { Suresh , Swati, Rishabh} Some times type can also be defined General Syntax is : [storage class] [type qualifier] enum [tag name] {enum list} id=initializer [.....]] Y Terms within [] are optional. Y Names of enumerators must be unique but numerical values can be same if explicitly assigned. Y If we do not explicitly assign values to enum names, the compiler by default assigns values starting from Oand further successive names are one greater than previous. PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANU] KHANNA (ASST. PROFESSOR) page 30 www.uptunotes.com E.g : enum color { red =2,, yellow=1 , green =1}; // An example program to demonstrate working of enum in C #include enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun}; int main( ) enum week day; day = Wed; printf("%d" day); return 0; } Output: 2 Another example program to demonstrate working // of enum in C #include enum year{Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec}; int main) { int i Output: 01234567891011 We can assign values to some name in any order. All unassigned names get value as value of previous name plus one. Hinclude enum day {sunday = 1, monday, tuesday = 5, Wednesday , Thursday = 10, friday,saturday} ; int main( ) printi("%d %d %d %d %d %d 9%", sunday, monday, tuesday, wednesday, thursday, friday, saturday); return 0; } Output: 12561011 12 All enum constants must be unique in their scope. For example, the following program fails in compilation. enum state {working, failed}; enum result {failed, passed}; int main() { retwm 0; } Output: Compile Error: 'failed' has a previous declaration as 'state failed’. PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANUJ KHANNA (ASST. PROFESSOR) page 34 www.uptunotes.com Ques 14. Why type checking is necessary? What is static and dynamic type checking? Explain type casting methods with examples. Ans : Data storage representations that are built into the computer hardware usually have no type information and the primitive operations on the data do no type checking. E.g : A particular word in the computer memory during execution of a program may contain the bit sequence 1100110101...0110.This may be an integer , a real ora sequence of chars, But hardware primitive operations over additions, subtractions etc. Cannot tell the type of data and so error detection becomes tough. That is the reason why type checking is necessary. So Type Checking means checking that each operation executed by a program receives the proper number of arguments of the proper data type. E.g.: before executing the assignment statement x = a + b *c, compiler ‘must check the compatibility of data types for each of the operations *, + an¢ Static Type checking is performed at translation or compile time of the program. Information is provided in declarations by the programmers. Information is as below: Y For each operation aumber, order, data types of its argument and results (that is Signature). ¥ For each variable the type of data object named. ¥ Type of each constant data object.(e.g. :2 is integer type , 6.5 is real , ‘d’ is char type constant. Advantages of static type checking: Y Static type checking includes all the operations that appear in any program statement, so all the possible execution paths are checked and further no need to test the code for data type errors. ¥ Type tags on data objects at run time not required. Y Increases the program efficiency and less memory consumption. ‘Dynamic Type checking is performed at the runtime of program. Here type tag for each data object is stored. E,g:: an integer variable may hold both integer value and integer tag. Operation is performed only if type tag of each argument is matched else an error is thrown. Languages like Perl and Prolog are designed to require dynamic type checking. In these languages no declaration of type is assumed Data type of variables may change during the execution time. Advantages of Type Checking: Y Flexibility in program design. ¥ Programmer is freed from concern about data type declarations. Disadvantages of dynamic type checking: Y Programs are difficult to debug, because data types at execution time of an operation are checked and operations on program execution path that are not executed are never checked. ¥ During program testing not all possible execution paths may be tested. ¥ Extra storage for type tag is required Y Mostly implemented in software because underlying hardware rarely supports dynamic type checking. STRONGLY typed languages: If we can detect all type of errors in a program, we say that the language is strongly typed. This provides more security to codes. We call a function f , with a signature f: S— R, type PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANU] KHANNA (ASST. PROFESSOR) page 32 www.uptunotes.com safe if execution of f cannot generate a value outside of R. E.g : C, C+¥ Java are strong] Type Casting (Type Conversion) ‘When any C expression or statement involves different data types e.g : multiplication of a float number by integer number , then to get the correct result in terms of values Type conversion / Type casting is required in programming. In this we change a variable of one data type to variable of another data type. ++ Type conversion is done implicitly by the compiler =* Type casting is performed explicitly by the programmer. (a) Type conversion : It is done when expression has variables of different data types. To evaluate the expression , data type is promoted(Widening) from lower to higher data type (or from higher to lower). ‘Type conversion is automatically performed. eg: float x int y x =y;// Here x will have the value 3.0 as automatically integer value is converted //to its equivalent floating point value. Conversion hierarchy of data types is as shown below : Tong double Higher level double Float .ed long int Long int Unsigned int Int Short, char Lower level ** When a char type is operated with an int type char is promoted to int. ** When a float type data is operated with an int , then int is promoted to float. ** When any operand is double then another operand is also converted to double Type casting : It is also called as forced conversion. It is done when value of higher data type is to be converted to lower data type. This conversion is under programmer's control , not in compiler’s control. Demotion (Narrowing) : float £= 3.5 ; inti; = f; Statement i= fresults in f to be demoted to type int , Le. the fractional part of f will be lost and I will contain 3 not 3.5 ; this is called down conversion/demotion. But result is not correct so explicit type casting is required. Explicit type casting is done by placing the target data type in parentheses followed by the variable name that has to be converted. Variable 2 = (data type) variable e.g : float salary ~ 1000.00 ; PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANU] KHANNA (ASST. PROFESSOR) page 33 www.uptunotes.com int tot_sal sal = (int ) salary * When floating point numbers are converted to integers , the digits after decimal are truncated. Ques 15.What are scalar data types and composite data types? Define the techniques for storage representation of integer values. Ans : Scalar data objects are those which have single attribute for its data object. E.g : An integer object x can have only a single integer value Generally scalar data types are dependent on hardware architecture. But Composite data objects for example a character string contains a sequence of characters as its data value, but may have other attributes such as a string size. as an additional attribute value. Integer Storage Representation: The set of integer values defined for the type forms an ordered subset, within some finite bounds of the infinite set of integers. C has four different integer specifications int, short, Jong and char Signature for various integer operations are as follows: (i) Arithmetic operations : Binop : integer x integer — integer Unaryop : integer > integer. (ii) Relational operations : relop : integer x integer —>boolean (ii) Assignment : integer x integer > void Three techniques for storage representation for integers are as below: © No Descriptor (ii) Descriptor stored in separate word (ii) Descriptor stored in same word. SIGN BIT NO DESRIPTOR 410111 Binary integer. In this no run time descriptor is available only value is stored. This is used in static type checking. @ 2 method is descriptor stored in separate memory location, with a pointer to the full word integer value. This representation is mostly used in LISP. But this doubles the memory requirements for a single integer data object. Advantage is that the value is stored using the built in hardware representation so that hardware arithmetic operations may be used. sensi | _| 011 nan Binary integer Descriptor stored in separate word PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANU] KHANNA (ASST. PROFESSOR) page 34 www.uptunotes.com In third representation descriptor and value are stored in a single memory block by decreasing the size of integer In this technique storage is conserved but the hardware arithmetic operations can not be used without first clearing the descriptor fiom the integer data object, performing the arithmetic and then reinserting the descriptor. Because a sequence of hardware instructions must be executed to perform a single arithmetic operations, arithmetic is inefficient. Ques 16. For a programming language like C/Java, find an example of a primitive operat @) Has an implicit argument. (b) Has a side effect (© Isundefined for some data objects in its specified domain @ That is self modifying. The object variable before the method name in the method call are called implicit parameters > The object on which you invoke a method is also as a parameter in the method call, because if you use a different abject in the method call, the operation is performed on a different object (ie., the behavior of the method is modified): harrysChecking.deposit(500); ‘momsSaving.deposit(500); The first call updates the balance instance variable in harrysChecking, while the second call updates the balance instance variable in momsSa (b) Suppose we want to write a method that modifies a variable of a primitive type (ie., a method with side-effect on variables). For example, we try to implement a method that increments a variable of type int: public static void increment(int p) { p =p +1: } > if we now invoke the increment method as follows: public static void main(String[] args) { int a = 10; increment(a); System.out.printin(a); // prints 10 3 > we see that the program prints 10, instead of 11, as we could have expected. This is because, during the invocation of the increment method, the value 10 stored in the local variable a is copied in the formal parameter p. The increment method modifies the formal parameter p, but does not modify the content of the local variable (©) Dangling reference in C and NULL pointers. (@) Increment and decrement operations in C and Java are self modifying. PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANU] KHANNA (ASST. PROFESSOR) page 35 www.uptunotes.com Ques 17. How are the character arrays declared and initialized? What are the various storage Representations for character arrays in system memory? ‘Ans : A character array is a sequence of characters stored in a contiguous memory allocation. Strings are actually one-dimensional array of characters terminated by a null character "0 ‘Thus a null-terminated string contains the characters that comprise the string followed by a nul ‘The following declaration and initialization create a string consisting of the word "Hello". To hold the null character at the end of the array, the size of the character array containing the string is one more than the number of characters in the word "Hello." char greeting[6] = {'H’, 'e', 'T,, I’, '0', \0" If you follow the rule of array initialization then you can write the above statement as follows: char greeting| | = "Hello"; Following is the memory presentation of the above defined string in C/C++ — Index ° a 2 2 ‘ s Variable H e 1 1 ° \o Address | omsesi | oasesz | oases | osse | oczess | oases Actually, you do not place the null character at the end of a string constant. The C compiler automatically places the 0" at the end of the string when it initializes the array. Character String data types are represented by following three storage methods: Y Fixed declared length Y Variable length to a declared bound. Y Unbounded length. Ina fixed declared length value assigned to the data object is always a character string of this length. Assignment of a new string value to the data object results in a length adjustment of new string by deletion of new characters or addition of blank characters to produce the string of proper length. Strings stored 4 characters per word Leta string is : char str[12]=" RELATIVITY” padded with blanks. R E A T/ OI v 1 T Y Ifactual value stored in the data object is a string of shorter length or even the empty stris during the execution the length of the string value of the data object may vary, but itis truncated if PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANU] KHANNA (ASST. PROFESSOR) page 36 www.uptunotes.com it exceeds the bound. In this storage at the header of memory block two extra information is stored that is maximum length of string and current length of string. 10 | 14 R E Li A T I Vv T T Y A character string data object may have a string value of any length an length may vary dynamically. @ —_ Unbounded with fixed allocations : String is stored at 4 characters per block Length at header of string. A pointer field points to first element of every next block. 10/R [E [L I[t Y Unbounded with variable allocations: Here string is stored as contiguous array of characters, terminated by the NULL character. R [E [L JA [T[I Ques 18. Define structured data objects & data types with examples. What are their specifications and operations performed? Ans : A data object that is constructed as a combination of other data objects called components is called structured data object or data structure. A component can be elementary or derived data type. E.g An array can have integer, float, char as its components or array can have pointers as its element. Array may have structures also as its elements or another array elements too, Specifications of Data Structure Types : 1. Number of components Y Fixed size data, if components are invariant during the life time. Generally implemented using static memory allocation. E.g : 1-D array .records. Y Variable size data if size of components may change during life time of data objects. Operations like in insertion , deletion are supported here using dynamic memory allocations. 2. Type of each component: ¥ Homogeneous: If all the components of data structure are of the same type. E.g : integer array, float array etc. Y Heterogeneous : [fall the components of data structure are of the different type.E.g : records, Class. PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANU] KHANNA (ASST. PROFESSOR) page 37 www.uptunotes.com 3. Names to be used for component selection: For an array name of an individual component may be aan integer subscript or sequence of subscripts for a data table. Names can be programmer defined or system defined. 4. Maximum number of components: For a variable size data structure such as a stack ,a maximum Size for the structure in terms of number of components may be specified. 5. Organization of components: Y Sequential representation : Contiguous memory allocations for fixed size data objects L-D array, 2-D array , n-D array stored in row major or column major form. Records, stacks, files are also having this organization. Row Major Form: Column Major Form ¥ Link representation : Pointers to other components for variable size data objects. Ques 19. What are various techniques for storage representations of data structures? Explain the ignificance and implementation of dope vector(descriptor). ‘Ans : Storage of the components of the structure and optional descriptor that stores some or all the attributes of the structure. Two basic representations are Sequential and Linked. In sequential representation data structure is stored in a single contiguous block of storage that includes both descriptor and components. Linked representation stores the data in several non contiguous blocks of storage , with the blocks linked together through pointers. A pointer holds the address of first location of next memory block. > Sequential representations are used for fixed size variables with static memory allocations. > Linked representations are used for variable size data with dynamic memory allocations. For a homogeneous structure such as an array that is stored sequentially, selection of a sequence of components from the structure is possible by these steps: (i) To select the first component of the sequence, use the base address + offset. (i) To advance the next component in sequence add size of current component to the location of the current PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANU] KHANNA (ASST. PROFESSOR) page 3g www.uptunotes.com Bote adclrese ts Lecotion 4 Ale] © Bate-addauess + op eet: (eR? Cas Lex) tary ee ° Dope Vectors is a data structure that is used by compilers to store some metadata about the array like its total size, the size of one unit also called stride of the array, ete, These are used to describe arrays and other similar structures that store multiple values of one datatype as a complete block of memory. It can also describe structures that contain arrays and similar structures as its component. Dope vectors help compilers to access the arrays with ease. Different checks that are implemented by compiler like Out of Bound check, datatype check,etc. are all possible because of dope vector associated with the array. PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANU] KHANNA (ASST. PROFESSOR) page 39 www.uptunotes.com ‘The following details are stored in the dope vector for a particular array: Lower Bound LBA) eo Subscript UB <— Upper Bound on Subseript 2 |< tower Bound fon SubseriotZ I< Upper Bound on SubseriptZ ee ‘Component Descriptor (Dope Vector) E denotes the size of one single array element like E = | for character, E = 4 for integers, ete. VO denotes the virtual starting memory of the attay inside the RAM. LUI denotes the starting lower bound of the array. VBI denotes the upper limit up to which the array is currently occupied. ‘UB2 denotes the upper limit up to which the array can be filled The details that a dope vector stores vary from one operating system fo another, but mostly it contains the following information regarding aw array. Rank or number of dimensions of array or ‘The base address of the array. The type of elements stored in the array. ‘The stride of the array. The extent of the array. There are many problems that are solved by using the concept of dope vectors with the arrays at the cost of a small computation overhead (fetching data from dope vector) like: Itis difficult to release the extra memory associated with the array without the use of dope vector. Suppose that we initially allocated 200KB of memory for the array. But when it was used it required only 150 Kb of memory. Releasing the extra memory becomes quite easy with the use of dope vector as it store the extent of the memory currently occupied by the array. Without the dope vectors itis very difficult to determine the number of elements int the array, since it stores the information of the total size of the array and the length of the stride. It can be used to calculate the total number of elements in the array, Concept of Virtual Origin is described as below : PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANU] KHANNA (ASST. PROFESSOR) page 40 www.uptunotes.com VIRTUAL ORIGIN: Elmont with Aude dani ° soa vector: So [roasts to ores Jo: Avodre (ALE) = (4- tox €)+ (ox &) = ( &-Lax®) Ks Addiess thot ddinnsst”D eassitet seat atby if it on pa Bue dlaneit inten bebe > 0): Oe at tated -VIRTUAL-ORI GIN: SO the Ovitnn biitdng cee oie = "spt Ow wuotiow Eas - Mocote a rey tu &! Pe cL Rigin (VO) = a-Lexe <* Cappers wRtuaAL © Stee we . at poss Hane ne Ve aie coil dae PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANUJ KHANNA (ASST. PROFESSOR) page 44 www.uptunotes.com Ques 20. What are records or structures? How are they implemented in memory? Ans : Record is another user-defined data type available in Pascal which allows you to combine data items of different kinds. Records consist of different fields. Suppose you want to keep track of your books ina library, you might want to track the following attributes about each book — Title , Author , Subject , Book ID Defining a Record To define a record type, you may use the type declaration statement. The record type is defined as — Here is the way you would declare the Book record ~ type Books = record - title: packed array [1..50] of char; ficld-n: field-typen; author: packed array [1.-50] of char; subject: packed array [1..100] of char; book id: integer; end; The record variables are defined in the usual way as var ri, r2, ... : record-name; In C language instead we use structures with keyword struct as described below: Structures are the user defined data types that is of heterogeneous nature , that means it can store information of different data types. Keyword struct is used to declare a structure. Declaration of structure: struct structure _ name { Data_type var-nmael; Data_type var-nmaet ; 35 Example: if we define a structure for a student, Initialization of structures: A structure can be then the related information can be :rollno, initialized in the same way as other data types name , course, fees. This structure can be are initialized. Initializing a structure means declared as = assigning some constants to the members of the struct student structure. If explicitly, then C automatically does t that. For int and float members, values are initialized int rollno ; to zero and character and string members are char name [ 20); initialized to “\0° by default. Initializers are enclosed char course [ 25] ; in curly braces separated by commas. float fees ; } ; struct student $1, $2 PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANU] KHANNA (ASST. PROFESSOR) page 42 www.uptunotes.com Example: ‘Accessing Members of a Structure. struct student { Dot operator is used to access the int rollno ; values of members with the help of char name [ 20 ]; variables in structure. char course [ 25] : float fee Syntax : struct_var. member_name ; } stud] = { 001, Vishal , B.Tech , 76000 } ; Example : OR Stud1.rolinoe = 001 Stud1.name= Vishal struct student stud! = { 001 , Vishal , B.Tech , Stud1.course = B.Tech 76000 } ; Stud1.fees Memory representation for structure /record: ¥ It consists of a single sequential block of memory in which the components are stored in sequence, Individual elements may need descriptors to indicate their data type or other attributes, but no run time descriptor for records is required. Y Component selection easy to implement because subscripts are known during translation rather than being computed during execution. Y The size and position of each component of record within the storage block is to be determined during translation. So offset of any component can be evaluated at compile time. Basic formula used to compute the location of the I component is : Lvalue( RD) = + Dc{(sizeof R.j) Where @is the base address of storage block representing Record R. R,jis the jth component. Ques 21. What are variant records, explain? Ams : A variant record is a record type that can have different sets of fields (ie variations) in different variables. The variations are chosen using a specified field as a tag. Such a record has one or more components that are common to all variants and then each variant has in addition several other components with names and data types that are unique to that variant. Here is a variant record implementation of the Transaction type type PaymentType is (Cash, Check, Credit); ~ The_Type is called the discriminant of the type type Transaction(The_Type: PaymentType := Cash) is record Amount: Integer; case The Type is when Cash => Discount: boolean; when Check => PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANU] KHANNA (ASST. PROFESSOR) page 43 KRISHNA INSTITUTE OF TECHNOLOGY, KANPUR CheckNumber: Positive; when Credit => CardNumber: String(1..5); Expiration: String(1..5); end case; end record; program BPVariantRecordDemo; This is the example of variant record. begin ‘ For Blood Pressure program to typ calculate patient's record based on PersonRec ~ record various other attributes. Age: Integer; case EyeColor: (Red, Green, Blue, Brown) of Red, Green: (WearsGlasses: Boolean); Blue, Brown: (LengthOfLashes: Integer); ends Ques 22. Discuss the importance and implementation of arrays both 1-D and 2-D arrays using pointers. ‘Ans : Consider the following program: Hinclude int mainQ) { int arr{5] In this program, we have a pointer ptr that points to the 0* element of the array. Similarly, we can also declare a 1,2.3,4,5}5 pointer that can point to whole array instead of only one element of the array. printf("%p\n", ptr); return 0; y Syntax: data_type (*var_name)[size_of_array]; Example: int (*ptr)[10]; Here pir is pointer that can point to an array of 10 integers. Since subscript have higher precedence than indirection, it is necessary to enclose the indirection operator and pointer name inside parentheses. Here the type of ptr is “pointer to an array of 10 integers’. Note : The pointer that points to the 0" element of array and the pointer that points to the whole array are totally different. The following program shows this: PR y of Sintegers #include int mainQ { " Poin Pointey fp ani ter 1 Pan fotfomtus HBare shows the pointer go an and inc ps 7 ee ee er a mee ere e gt tote eo ati fe Nag) Page 44 int (" intkRISHINA INSTITUTE OF TECHNOLOGY, KANPUR KRISHNA INSTITUTE OF TECHNOLOGY, KANPUR 3000-3004 =«3008 «30123016 4500 Pointer to an array points to an array, so on dereferencing it, we should get the array_and the name of array denotes the base address. So whenever a pointer to an array is dereferenced, we get the base address of the array to which it points. Pointers and two dimensional Arrays: In a two dimensional array, we can access each element by using two subscripts, where first subscript represents the row number and second subscript represents the column number. The elements of 2-D array can be accessed with the help of pointer notation also. Suppose arr is a 2-D array, we can access any element arr/i]/j] of the array using the pointer expression *(*(arr + i) + j). ‘Now we'll see how this expression can be derived. Let us take a two dimensional array arr[3] [4]: int arr[3][4] = { {1, 2, 3, 4}, (5, 6, 7, 8}, (9, 10, 11, 12} }s Since memory in a computer is organized linearly it is not possible to store the 2-D array in rows and columns. The concept of rows and columns is onty theoretical, actually, a 2-D array is stored in row- major order ie rows are placed next to each other. The following figure shows how the above 2-D array will be stored in memory. In general we cam write arr + i Points to # element of arr -> Points to #* 1-D array © Since arr + i points to #* element of arr, on dereferencing it will get # element of arr which is of course a 1-D array. Thus the expression *(arr + i) gives us the base address of ?* 1-Darray. + We know, the pointer expression *(arr + i) is equivalent to the subscript expression arr{i]. So *(arr + i) which is same as arr[i] gives us the base address of i 1-D array. “(arr +0) - arr[0} - Base address of 0* 1-D array - Points to 0° element of 0° 1-D array - 5000 *{arr+ 1) - arr[i] - Base address of 1" 1-D array - Points to 0° element of 1” 1-D array - 5016 “(arr + 2) - arr[2} ~ Base address of 2" 1-D array ~ Points to 0° element of 2" 1-D array - 5032 PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANUJ KHANNA (ASST. PROFESSOR) page 45 KRISHNA INSTITUTE OF TECHNOLOGY, KANPUR Note: Both the expressions (arr +) and *(arr + j) are pointers, but their base type are different. The base type of (arr + i) is ‘an array of 4 units’ while the base type of *(arr + i) or arr] is int.dereferencing this expression we can get the j**element of the i* I-D array. arr Points to 0" 1-D array ‘arr Points to 0" element of 0" 1-D array (arr+ Points to i* 1-D array “(arr + i) Points to 0" element of i® 1-D array “(arr + i) + j) Points to j* element of i* 1-D array *(*(arr+i)+j) | Reprents the value of j" element of i* 1-D array Ques 23.Explain dangling reference with reasons of its occurrence in the code. Ans : Dangling pointers in computer programming are pointers that pointing to a memory location that has been deleted (or freed). ¥ Dangling pointers arise during object destruction, when an object that has an incoming reference is deleted or deallocated, without modifying the value of the pointer, so that the pointer still points to the memory location of the deallocated memory. ¥ The system may reallocate the previonsly freed memory, unpredictable behavior may result as the memory may now contain completely differentdata. Reasons of daneling pointers (a) Variable goes Out of Scope #include int main As str character pointer is non-visible in Outer Block of main, £ and character pointer to pointer strPtr is still pointing to same char **strPtr; invalid memory location in Outer block, then character { pointer to pointer strPtr becomes "Dangling Pointer”. char *str ="Hello! strPtr = &str; Str is in the inner block so itis out of the scope of Outer Block. } Whereas pointer to pointer strPtr is declared in outer block so it is visible in both outer as well as inner block. printf("%s", *strPtr); } (b) De-allocating or free variable memory #include ‘fimclude Here we have declared the character pointer *str and character int main pointer to pointer strPtr. After assigning the address of str to t strPtr we have de-allocated memory using free function. As soon char **stPtr; char *str = "Hello!"; suPtr = &str; as memory is de-allocated for character pointer str, character pointer to pointer strPir becomes dangling pointer-If we write aes the printf before free function then strPtr will be no PRINCIPI FES OF FegcRaMMING LANGUAGES §1Gfhpffdly poi ANUJ KHANNA (ASST. PROFESSOR) page 46 os" KRISHNA INSTITUTE OF TECHNOLOGY, KANPUR KRISHNA INSTITUTE OF TECHNOLOGY, KANPUR (©) Return Local Variable in Funetion Call #include #include str falls out of scope function call char *getHello() is now a dangling pointer Here we are returning an address which was char *getHello() a local variable (str), which would have gone out of scope by { the time control was returned to the calling function. char str[10]; strepy(str,"Hello! return(str); Attempts to read from the pointer may still retum the correct } value (Hello!) for a while after calling function getFfello, but any functions called thereafter will overwrite the stack storage allocated for str with other values and the pointer would no longer work correctly. If a pointer to str must be retuned, str must have scope beyond the function—it mightbe declared t as static. int main { printi("%s", getHello); Ques 24. Explain Union with an example. What are its properties? Ans : A union is a special data type available in ©.that allows to store different data types in the same memory location. You can define a union with many miembers, but onl¥ ore member can contain a value at any given time. Unions provide an efficient way of Using the same memory Jocation for multiple-purpose. To define a union, you must use the union statemefitin the same way as you-did while defining a structure. The union statement defines a new data type with more than one member for your program. The format of the union statement is as follows — ‘union [union tag] { So +i member definition; member definition; member definition; } [one or more union variables]; The union tag is optional and each member definition is a normal variable definition, such as inti; or float £ or any other valid variable definition union Data { int i; The memory occupied by a union will be large float f; enough to hold the largest member of the union. For char str[20]; example, in the above example, Data type will } data; occupy 20 bytes of memory space because this is the maximum space which can be occupied by a character string. The following example displays the total memory size occupied by this union Data, PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANU] KHANNA (ASST. PROFESSOR) page 47 KRISHNA INSTITUTE OF TECHNOLOGY, KANPUR #include #include ‘union Data { int i; float f; char str[20]; B int main() { union Data data; printf( "Memory size occupied by data : %d\n", sizeof(data)); return 0; 3 Accessing Union Members To access any member of a union, we use the member access operator (.). The member access operator is coded as a period between the union variable name and the union member that we wish to access. You would use the keyword union to define variables of union type. The following example shows how to use unions ina program — #include #include union Data { inti; float f; char str[20]; B int main() { union Data data; data.i= 10; data.f= 220.5; strepy( data.str, "C Programming"); printf "data. : %d\n", data.i); printf "data.f : %f\n", data.f); printf "data.str : %s\n", data.str); return 0; Ques 25. Write short notes on the following: (a) Associative arrays (b) Short Circuiting in Boolean expressions (c) Iterations PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANU} KHANNA (ASST. PROFESSOR) page 4g KRISHNA INSTITUTE OF TECHNOLOGY, KANPUR Aas : (a) Associative arrays: Associative arrays, also called maps or dictionaries, are an abstract data type that can hold data in (Key; valve) pairs. You can think of associative arrays like a list of phone numbers, In this list, you can look up a person's name by finding their phone number. The name is the valve and the number is the key. The index for an associative array is called the key, and its type is called the KeyType, Associative arrays have two important properties. Every key can only appear once, just like every phone number can only appear once in a directory. And, every key can only have one value, just like every phone number can only refer to one person. The associative array has four basic operations. Function Name insert(key, value) Add a (key, value) pair to the associative array remove(key) Remove the key's p: the associative array update(key, value) | Assigns/updates the value to/of the existing key Tookup(key) Returns the valve assigned to this key Example of associative array in Java Script An associative array is declared or dynamically created. We can ereate it by assigning a literal to a variable. var amr = { "one": 1, "two": 2, "three": 3 }s Unlike simple arrays, we use curly braces instead of square brackets. This has implicitly created a variable of type Object:The content is accessed by keys, whatever the method used to declare the array. var y= arr{"one"]; So we can create an associative array with the Object reserved word, then and assign keys and values: var 0 = new Object; o["one"] = 1; of"two"] = 25 of"three"] = 3; for(var iin 0) { document.write (i + "=" + off] +
); } Output: one=1 two=2 three=3, PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANUJ KHANNA (ASST. PROFESSOR) page 49 KRISHNA INSTITUTE OF TECHNOLOGY, KANPUR (i) Short Circuiting in Boolean Expressions: In computer science, a Boolean expression is used expression in @ programming language that produces a Boolean value when evaluated, that is one of true or false. A Boolean expression may be composed ofa combination of the Boolean constants true or false, Boolean-typed variables, Boolean-valued operators, and Boolean-valued functions.Most programming languages have the Boolean operators OR, AND and NOT; in C and some newer languages, these are represented by "|" (double pipe character), "S&&" (double ampersand) and "!" (exclamation point) respectively, Short circuiting is something that will happen when your program is running and it hits a conditional. A short circuit in logic is when you know for sure that an entire complex conditional is either true or false before you evaluate the whole thing. R : When the Python interpreter scans or expression, it takes first statement and checks to see if it is true. If the first statement is true, then Python returns that object's value without checking the second statement. The program does not bother with the second statement. If the first value is false, only then Python checks the second value and then result is based on second half. AND : For an and expression, Python uses a short circuit technique to check if the first statement is false then the whole statement must be false, so it returns that value. Only if the first value is true, it checks the second statement and returns the value. ‘An expression containing and and or stops execution wien the truth value of expression has been achieved, Evaluation takes place from left to right. Gi) Tterations: When designing programs, there may be some instructions that need repeating. Iteration is the repetition of a process in order to generate a (possibly unbounded) sequence of outcomes. The sequence will approach some end point or end value. Each repetition of the process isa single iteration, and the outcome of each iteration is then the starting point of the next iteration. This is known as iteration, and is implemented in programming using FOR , WHILE statements. and DO-WHILE. Iteration allows us to simplify our algorithm by stating that we will repeat certain steps until told otherwise. This makes designing algorithms quicker and simpler because they don’t have to include lots of unnecessary steps. aso forifrom1to3 //loop three times t a J/ add the current value of i to a 3 print a // the number 6 is printed (0 + 1; 1 +2; 3 +3) Ques 26. What are guarded statements? Aas In 1975, Dijkstra proposed an altemative set of selection and looping constructs for programming languages. The idea of guarded commands introduced nondeterminism to programs. A guarded command is a statement, or list of statements, that is "guarded" by a boolean expression. For example: PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANU] KHANNA (ASST. PROFESSOR) page 59 KRISHNA INSTITUTE OF TECHNOLOGY, KANPUR x>Sy> max := x; (guard) (command) The idea being that the command cannot be executed unless the guard evaluates to true. So far, this construct is nothing special. What adds nondeterminism is how these guarded commands are used for selection and looping. Dijkstra's selection structure looks like this: if -> < statement > [] > < statement > [] -> < statement > fi There are several guarded commands in the structure, separated by the square brackets. The selection goes like this: if none of the boolean expressions evaluate to true, the program exits with an error. If one of the expressions evaluate to true, then the statement associated with that guard is executed. Finally, if ‘more than one of the expressions are true, then one of the expressions is nondeterministically chosen, and the command associated with it is performed. Here's an example: suppose you want to create a program that gets the maximum value between x and y. Using guarded commands, we would write the program like this: ifx>=y > max:=x; Dy>=x> max :=y; Fi That is, max is assigned whichever is greater of x or y. If x and y are the same value, then it does not matter whether max gets assigned either x or y. The looping structure is similar: do > < statement > [] -> < statement > {] > < statement > od The semantics is that all the expressions are evaluated simultaneously, if one of the expressions is tme, then the statement associated with it is performed. If more that one is true, then one statement is picked non deterministically. Finally, if all of the expressions evaluate to false, the program exits the loop. Both Ada and Hoare's CSP (Critical Section Problem )use guarded commands as a way to handle concurrency. PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANU] KHANNA (ASST. PROFESSOR) page 51 KRISHNA INSTITUTE OF TECHNOLOGY, KANPUR UNIT -3 » Sequence control » Subprograms Design Issues » Activation Records » Semantics of Call and Return, Implementing Simple Subprograms Vv Local Referencing v Parameter Passing Methods Overloaded Methods v » Generic Methods and Design Issues for Functions » Stack - Dynamic Local Variables > Nested Subprograms » Static and Dynamic Scoping. PRINCIPLES OF PROGRAMMING LANGUAGES (RCS 503) MR. ANUJ KHANNA (ASST. PROFESSOR) page 52

You might also like