complete report download programing

26
THE ROLE OF PROGRAMMING LANGUAGES (ASSIGNMENT OF) PRINCIPLES OF PROGRAMMING LANGUAGE Course in B.TECH COMPUTER SCIENCE Prepared By Group 2 AKASH GOYAL(10115008) AMANPREET KAUR(10115009) AMAN KUMAR(10115010) ANIL SINGH(10115011) ANKIT SHUKLA(10115012) ANKIT YADU(10115013) ANUPAM MAURYA(10115014) DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING NATIONAL INSTITUTE OF TECHNOLOGY, RAIPUR RAIPUR-492001, C.G. , India 2012-2013

Upload: nagireddy1234

Post on 26-May-2017

237 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: Complete Report download programing

THE ROLE OF PROGRAMMING LANGUAGES

(ASSIGNMENT OF) PRINCIPLES OF PROGRAMMING LANGUAGE

Course in B.TECH COMPUTER SCIENCE

Prepared By Group 2

AKASH GOYAL(10115008)

AMANPREET KAUR(10115009)

AMAN KUMAR(10115010)

ANIL SINGH(10115011)

ANKIT SHUKLA(10115012)

ANKIT YADU(10115013)

ANUPAM MAURYA(10115014)

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

NATIONAL INSTITUTE OF TECHNOLOGY, RAIPUR

RAIPUR-492001, C.G. , India

2012-2013

Page 2: Complete Report download programing

2

Acknowledgement

It will be simple to name all those people who helped us to get this report done, however it will be tough to thank them enough. We will nevertheless try. . .

We would like to gratefully acknowledge the enthusiastic supervision and guidance of Prof. Amit Ku. Trivedi for the ideas that led to this work, for his timely comments, guidance, support and patience throughout the course of this work. He is our source of inspiration

Page 3: Complete Report download programing

3

Contents Course contents Page No.

Introduction 4 Levels Of Programming Language 7 Programming Paradigms 11 Language Implementation 16 Compilation vs. Interpretation 20 Exercises 21

Page 4: Complete Report download programing

4

Introduction

Programming Languages are notations. They are used for specifying, organizing, and reasoning about computations. Just as English compositions range from notes to sonnets, programs range from prototypes that are used once and forgotten to production tools that are shared and supported. This range of needs has motivated the creation of hundreds of programming languages.

Language designers balance:

• Making computing convenient for people with • Making efficient use of computing machines

Convenience comes first. Without it, efficiency is irrelevant.

Programming languages have evolved far beyond their origins in machines. As machine language is unintelligible.Languagescan help not only by improving the readability of individual program fragments, but by providing ways of organizing and managing large programs.

Levels of Programming Language

There is only one programming language that any computer can actually understand and execute: its own native binary machine code. This is the lowest possible level of language in which it is possible to write a computer program. All other languages are said to be high level or low level according to how closely they can be said to resemble machine code.

In this context, a low-level language corresponds closely to machine code, so that a single low-level language instruction translates to a single machine-language instruction. A high-level language instruction typically translates into a series of machine-language instructions.

Low-level languages have the advantage that they can be written to take advantage of any peculiarities in the architecture of the central processing unit (CPU) which is the "brain" of any computer. Thus, a program written in a low-level language can be extremely efficient, making optimum use of both computer memory and processing

Page 5: Complete Report download programing

5

time. However, to write a low-level program takes a substantial amount of time, as well as a clear understanding of the inner workings of the processor itself. Therefore, low-level programming is typically used only for very small programs, or for segments of code that are highly critical and must run as efficiently as possible.

High-level languages permit faster development of large programs. The final program as executed by the computer is not as efficient, but the savings in programmer time generally far outweigh the inefficiencies of the finished product. This is because the cost of writing a program is nearly constant for each line of code, regardless of the language. Thus, a high-level language where each line of code translates to 10 machine instructions costs only one tenth as much in program development as a low-level language where each line of code represents only a single machine instruction.

In addition to the distinction between high-level and low-level languages, there is a further distinction between compiler languages and interpreter languages. Let's take a look at the various levels.

Absolute Machine Code

The very lowest possible level at which you can program a computer is in its own native machine code, consisting of strings of 1's and 0's and stored as binary numbers. The main problems with using machine code directly are that it is very easy to make a mistake, and very hard to find it once you realize the mistake has been made.

Assembly Language

Assembly language is nothing more than a symbolic representation of machine code, which also allows symbolic designation of memory locations. Thus, an instruction to add the contents of a memory location to an internal CPU register called the accumulator might be add a number instead of a string of binary digits (bits).

No matter how close assembly language is to machine code, the computer still cannot understand it. The assembly-language program must be translated into machine code by a separate program called an assembler. The assembler program recognizes the character strings that make up the symbolic names of the various machine operations, and substitutes the required machine code for each instruction. At the same time, it also calculates the required address in memory for each symbolic name of a memory location, and substitutes those addresses for the names. The final result is a machine-language program that

Page 6: Complete Report download programing

6

can run on its own at any time; the assembler and the assembly-language program are no longer needed. To help distinguish between the "before" and "after" versions of the program, the original assembly-language program is also known as the source code, while the final machine-language program is designated the object code.

If an assembly-language program needs to be changed or corrected, it is necessary to make the changes to the source code and then re-assemble it to create a new object program.

Compiler Language

Compiler languages are the high-level equivalent of assembly language. Each instruction in the compiler language can correspond to many machine instructions. Once the program has been written, it is translated to the equivalent machine code by a program called a compiler. Once the program has been compiled, the resulting machine code is saved separately, and can be run on its own at any time.

As with assembly-language programs, updating or correcting a compiled program requires that the original (source) program be modified appropriately and then recompiled to form a new machine-language (object) program.

Typically, the compiled machine code is less efficient than the code produced when using assembly language. This means that it runs a bit more slowly and uses a bit more memory than the equivalent assembled program. To offset this drawback, however, we also have the fact that it takes much less time to develop a compiler-language program, so it can be ready to go sooner than the assembly-language program.

Interpreter Language

An interpreter language, like a compiler language, is considered to be high level. However, it operates in a totally different manner from a compiler language. Rather, the interpreter program resides in memory, and directly executes the high-level program without preliminary translation to machine code.

This use of an interpreter program to directly execute the user's program has both advantages and disadvantages. The primary advantage is that you can run the program to test its operation, make a few changes, and run it again directly. There is no need to recompile because no new machine code is ever produced. This can enormously speed up the development and testing process.

Page 7: Complete Report download programing

7

On the down side, this arrangement requires that both the interpreter and the user's program reside in memory at the same time. In addition, because the interpreter has to scan the user's program one line at a time and execute internal portions of itself in response, execution of an interpreted program is much slower than for a compiled program.

Programming Paradigms

Programming languages

• A Programming language is a notational system for describing tasks/computations in a machine and human readable form.

• Most computer languages are designed to facilitate certain operations and not others: numerical computation, or text manipulation, or I/O.

• More broadly, a computer language typically embodies a particular programming paradigm.

Characteristics of a programming language :

Every language has syntax and semantics:

• Syntax : The syntax of a program is the form of its declarations, expressions, statements and program units

• Semantic : The semantic of a program is concerned with the meaning of its program.

Which programming language?

• Since a task can be solved in different ways (paradigms), the language used to describe the solution differs in abstractions, structures due to the way in which the problem is solved.

• There is no theory that dictates the best paradigm to solve a particular problem.

• Efforts by Sebesta in his Concepts ofProgramming Languages book:

Page 8: Complete Report download programing

8

• He based his evaluation criteria on three factors and 9 characteristics.

• The three criteria (R,W,R) are:

� Readability � Writability � Reliability

• The nine characteristics are:

Simpilicity/orthogonality (R,W,R):

• “Orthogonality in a programming language means that a relatively small set of primitive constructs can be combined in a relatively small number of ways to build the control and data structures of the language” [Sebesta]

• Relatively small set of primitive constructions combined in a number (of logically consistent) ways to provide the required control and data structures.

• The concepts of a programming language do not interfere with each other: different methods of passing parameters.

• Non-orthogonality : means exceptions to the general language rules, which make it harder to learn. It means that you cannot combine language features in all possible ways.

• Examples of non-orthogonal languages:

o Arrays in Perl4 can't contain other arrays.

o In C, parameters can be passed by value, unless they are arrays, in which case they are passed by reference.

� Control structures (R,W,R) � Control structures (R,W,R) � Data types and structures (R,W,R) � Syntax design (R,W,R) � Support for abstraction (,W,R) � Expressivity (,W,R):

• Programming languages with poor support for abstraction and weak primitives will have poor writability.

Page 9: Complete Report download programing

9

� Type checking (,,R) � Exception handling (,,R) � Restricted aliasing (,,R):

• Example : (C)

int salary, *p_salary;

salary = 98000;

p_salary = &salary;

salary and *p_salary are aliases.

Characteristics \Criteria Readability Writability Reliabiliity Synatx Design � � � Control Structures � � � Data Types � � � Simplicity/Orthogonality � � � Abstraction � � Expressivity � � Type Checking � Exception Handling � Restricted Aliasing �

• Maintainability

oFactoring: The ability to group related features into a single unit. Use subroutines to group related computations units so they can be re-used in different parts of the application.

oLocality: The ability to implement information hiding so that changes to a grouping (either control or data) are transparent.

• Cost

o Programmer training

o Software creation

Page 10: Complete Report download programing

10

o Compilation

o Execution

o Compiler cost

o Poor reliability

o Maintenance

• Others: portability and generality

Programming paradigms

• The paradigms are not exclusive, but reflect the different emphasis of language

designers. Most practical languages embody features of more than one paradigm.

• Classification :

Imperative/Algorithmic Declarative Declarative Object -Oriented Functional Prog. Logic Prog. ALGOL LISP Prolog SmallTalk COBOL Haskell Simula PL/1 ML C++ ADA Miranda JAVA C APL Modula-3

Imperative paradigms

• It is based on commands that update variables in storage. The Latin word imperare means “to command”.

• The language provides statements, such as assignment statements, which explicitly change the state of the memory of the computer.

Page 11: Complete Report download programing

11

• This model closely matches the actual executions of computer and usually has high execution efficiency.

• Many people also find the imperative paradigm to be a more natural way of expressing themselves.

Functional programming paradigms

• In this paradigm we express computations as the evaluation of mathematical functions.

• Functional programming paradigms treat values as single entities. Unlike variables, values are never modified. Instead, values are transformed into new values.

• Computations of functional languages are performed largely through applying functions to values, i.e., (+ 4 5).

Logic programming paradigms

• In this paradigm we express computation in exclusively in terms of mathematical logic.

• While the functional paradigm emphasizes the idea of a mathematical function, the logic paradigm focuses on predicate logic, in which the basic concept is a relation.

• Logic languages are useful for expressing problems where it is not obvious what the functions should be.

• For example consider the uncle relationship: a given person can have many uncles, and another person can be uncle to many nieces and nephews.

• Let us consider now how we can define the brother relation in terms of simpler relations and properties father, mother, and male. Using the Prolog logic language one can say:

brother(X,Y) /* X is the brother of Y */

Page 12: Complete Report download programing

12

/* if there are two people F and M for whi ch*/

father(F,X), /* F is the father of X */

father(F,Y), /* and F is the father o f Y */

mother(M,X), /* and M is the mother of X */

mother(M,Y), /* and M is the mother of Y */

male(X). /* and X is male*/

The Object-Oriented Paradigm

• OO programming paradigm is not just a few new features added to a programming language, but it a new way of thinking about the process of decomposing problems and developing programming solutions

• Alan Kay characterized the fundamental of OOP as follows:

� Everything is modeled as object � Computation is performed by message passing: objects communicate with

one another via message passing. � Every object is an instance of a class where a class represents a grouping

of similar objects. � Inheritance: defines the relationships between classes.

• The Object Oriented paradigm focuses on the objects that a program is representing, and on allowing them to exhibit "behavior ".

• Unlike imperative paradigm, where data are passive and procedures are active, in the O-O paradigm data is combined with procedures to give objects, which are thereby rendered active.

Concurrent programming

• Improve performance

Page 13: Complete Report download programing

13

• Multiprogramming systems attempt to utilize resources that would otherwise be wasted, by running two or more jobs concurrently.

• Multiaccess systems extend this principle, allowing many jobs to be run, each on behalf of a user at an interactive terminal.

• Concurrency can be classified into:

o Apparent concurrency: single processor (interleaved execution of concurrent tasks)

o Real concurrency: multiprocessor environment

• Issues :

o How to synchronize the interactions among concurrently executing processes to maintain the internal data integrity.

o Another problem is to schedule the racing processes for a limited set of shared resources.

Page 14: Complete Report download programing

14

Page 15: Complete Report download programing

15

LANGUAGE IMPLEMENTATION: BRIDGING THE GAP

A programming language implementation is a system for executing programs written in a programming language.

There are two general approaches to programming language implementation:

Interpretation : An interpreter takes as input a program in some language, and performs the actions written in that language on some machine.

Compilation : A compiler takes as input a program in some language, and translates that program into some other language, which may serve as input to another interpreter or another compiler.

A compiler does not directly execute the program. Ultimately, in order to execute a program via compilation, it must be translated into a form that can serve as input to an interpreter.

When a piece of computer hardware can interpret a programming language directly, that language is called machine code. A so-called native code compiler is one that compiles a program into machine code. Actual compilation is often separated into multiple passes, like code generation (often for assembler language), assembling (generating native code), linking, loading and execution.

If a compiler of a given high level language produces another high level language it is called translator (source to source translation), which is often useful to add extensions to existing languages or to exploit good and portable implementation of other language (for example C), simplifying development.

Many combinations of interpretation and compilation are possible, and many modern programming language implementations include elements of both. For example, the Smalltalk programming language is conventionally implemented by compilation into bytecode, which is then either interpreted or compiled by a virtual machine (most popular ways is to use JIT or AOT compiler compilation). This implementation strategy

Page 16: Complete Report download programing

16

has been copied by many languages since Smalltalk pioneered it in the 1970s and 1980s.

Interpreter

An interpreter normally means a computer program that executes, i.e. performs, instructions written in a programming language. An interpreter may be a program that either

1. executes the source code directly 2. translates source code into some efficient intermediate representation (code) and

immediately executes this 3. explicitly executes stored precompiled code[1] made by a compiler which is part

of the interpreter system

Early versions of the Lisp programming language and Dartmouth BASIC would be examples of type 1. Perl, Python, MATLAB, and Ruby are examples of type 2,

while UCSD Pascal is an example of type 3.

Source programs are compiled ahead of time and stored as machine independent code, which is then linked at run-time and executed by an interpreter and/or compiler (for JIT systems). Some systems, such as Smalltalk, contemporary versions of BASIC, Java and others, may also combine 2 and 3.

While interpreting and compiling are the two main means by which programming languages are implemented, these are not fully mutually exclusive categories, one of the reasons being that most interpreting systems also perform some translation work, just like compilers. The terms "interpreted language" or "compiled language" merely mean that the canonical implementation of that language is an interpreter or a compiler; a high level language is basically an abstraction which is (ideally) independent of particular implementations.

Page 17: Complete Report download programing

17

Program Output

Input

Fig : An Interpreter takes both a program and its input, and produces output .

Example:

Function eval(E) =

If E is the constant I then i

Else If E is the sum of E1 and E2 then eval(E1) + eval(E2)

Else If E is the product of E1 and E2 then eval(E1) + eval(E2)

Else If E is the sum of E1 and (product of E2 and E3) then eval(E1) + eval(E2)*eval(E3)

This Interpreter computes the value of an expression by examining its structure. The value of the expression 3 is 3.

The value of 4*5 is computed by extracting subexpressions4 &5, computing their values, and multiplying them. Similarly, 3+4*5 is the sum of 3 and 4*5, so the interpreter computes its value by adding the values of 3 and 4*5.

Compiler

A compiler is a computer program (or set of programs) that transforms source code written in a programming language (the source language) into another computer language (the target language, often having a binary form known as object code). The most common reason for wanting to transform source code is to create an executable program.

The name "compiler" is primarily used for programs that translate source code from a high-level programming language to a lower level language (e.g., assembly language or machine code). If the compiled program can run on a computer whose CPU or operating system is different from the one on which the compiler runs, the compiler is known as a cross-compiler. A program that translates from a low level language to a

Interpreter

Page 18: Complete Report download programing

18

higher level one is a decompiler. A program that translates between high-level languages is usually called a language translator, source to source translator, or language converter. A language rewriter is usually a program that translates the form of expressions without a change of language.

A compiler is likely to perform many or all of the following operations: lexical analysis, preprocessing, parsing, semantic analysis (Syntax-directed translation), code generation, and code optimization.

Program faults caused by incorrect compiler behavior can be very difficult to track down and work around; therefore, compiler implementors invest significant effort to ensure the correctness of their software.

The term compiler-compiler is sometimes used to refer to a parser generator, a tool often used to help create the lexer and parser.

Fig: A diagram of the operation of a typical multi-language, multi-target compiler

Page 19: Complete Report download programing

19

Example:

Instruction Form Action

a := a*a a is multiplied to itself and the result is assigned to a

x := x*y x is multiplied to itself and the result is assigned to x

p := p – q q is subtracted from p and the result is assigned to p

The instructions listed here mey be demonstrated by considering the Fortran expression

B**2 – 4.0*A*C

Which translates into a sequence of assembly instructions as follows:

R1 := B

R1 := R1*R1

R2 := 4.0

R3 := A

R2 := R2*R3

R3 := C

R2 := R2*R3

R1 := R1 – R2

When run, these instructions assign R1 the value of the Fortran expression.

What runs is the target code, consisting of the sequence of target instructions, not the source program text, consistinf of the Fortran expression.

Source Program

---------------------------------------------------------------------------------------------------------------------

Input Output

Fig: A source program is translated into a target p rogram, which is run

Compiler

Target

Code

Page 20: Complete Report download programing

20

Compilation vs Interpretation: A Comparison

A static property of a program is a property that is evident from the program text. A dynamic property is evident only upon running the program . Compiled languages have a bias toward static properties, since all compiling decisions are made using the source text at translation time. Interpreted languages can deal with dynamic properties.

Compilation & Interpretation can be compared as follows:

• Compliation can be more efficient than interpretation: Both compilation & interpretation impose some performance penalties, compared to carefully tailored machine code, written by hand. Compilation can, however be an order of magnitude faster than interpretation for the same programming language. The performance penalties due to compilation take two forms:

1. Machine time is needed to compile a source program into target code 2. The target code created by a compiler typically takes longer to run and

occupies more space than carefully written machine code. Unlike, a compiler, which translates the source program once and for all, an interpreter examines the program repeatedly. This repeated examination is a source of inefficiency.

• Interpretation can be more flexible than compilation: The repeated examination of the source program by an interpreter allows interpretation to be more flexible than compilation. An interpreter directly runs the source program, so it can allow programs to be changed “on the fly” to add features or correct errors. Furthermore, an interpreter works with the source text, so it can pinpoint an error in the source text and report it accurately. However, this is at cost of the overhead of the residency requirement of the interpreter during the run-time completely.

With a compiler, on the other hand, all translation is completed before the target program os run, whch prevents the target program form being readily adapted as it runs.In practice, a language can be implemented using a compilation of the two technques.

Page 21: Complete Report download programing

21

Exercises

1.1- In word describe a program to read a sequence of integers and to write the integers that appear one or more times in the input sequence. For example, if the input sequence is 617, 201 , 415, 201 , then 201 mu st appear just once in the output.

Solution-

1. Take the input from the user in the form of an array. 2. Take another array for storing the output of the program. 3. Now take a loop for traversing the given array . 4. As soon as we get a number check if it is present in the output array or not. 5. If it is already present in the output array ignore it 6. Else store it in the output array.

1.3- Describe solution to the following variants of Q3

a) Output one copy of only the duplicates in a list of elements. b) Count the number of times an element appears in the list.

Solution-

1. In the previous problem when we check whether the element is present in the output array then if it is present in the output array then store it in the duplicates array.

2. While checking in the output also check it in the duplicates array. If it is there then don’t copy it in duplicates array.

b)

1. now while checking it in the output array if it is present in the output array just increase the counter array value at the same index as the index of the element in the output array.

Page 22: Complete Report download programing

22

1.4-In the language of your choice, write a program to read two integers m and n and produce the desired result without using multip lication and division. Use repeated additions and subtractions instead.

a) m * n b) m div n c) m mod n

solution-

program in c++

void main()

{

int m, n, i, p=0, q=0;

cout<< “enter two numbers”

cin>>m >>n;

for(i=1; i<=n; i++)

{

p=p+m;

}

cout<< “ m* n= “<< p;

int k=m, l=n;

while( k> l)

{

k = k – l ;

q ++;

}

cout<< “ m div n = “ << q ;

Page 23: Complete Report download programing

23

cout<< “ m mod n = “<< k;

}

1.5- How would you test the program in Exercise 1.4 ?

We will test the programs in 1.4 by various methods-

a). code inspection by other people

b). program testingwith different sets of input

1.6- Describe how addition and multiplication of co mplex numbers can be implemented in terms of operations on real numbers.

Complex addition

1. read R[1], I[1] 2. read R[2], I[2] 3. R[3]=0, I[3]=0 4. R[3]=R[1] + R[2], I[3]= I[1] + I[2] 5. Write R[3], I[3] 6. Halt

Complex multiplication

1. read R[1], I[1] 2. read R[2], I[2] 3. R[3]=1, I[3]=1 4. R[3]=(R1*R2) – (I1*I2), I[3]=(R1*I2) + (R2*I1) 5. Write R[3], I[3] 6. Halt

1.7 Implement floating point addition in terms of i nteger arithmetic operations. Represent floating point numbers as pairs of intege rs(m,n), where m is a four-digit integer; that is, either 1000<= m <= 9999, or -9999<= m<= -1000. The pair

Page 24: Complete Report download programing

24

(m,n) represents m*pow(10, n-4). For example, (3142 ,1) represents 3142*pow(10,1-4) = 3.142

1. read (m,n)

1.8- The Rambler language is an extension of the RA M instruction set. It allows names to be used instead of memory locations. Thus, a name x can be used instead of M[j], so read (x) and x:=y+z are allowed. Further, in addition to >=, the relations<, <=, =, !=, and > are allowed in conditi onals. Do Exercise 1.4 using Rambler.

(a) m * n

1. read(m)

2. read(n)

3. z = 0

4. z = z + m

5. n = n - 1

6. if n>= 1 goto 4

7. Write z

8. Halt

(b) m div n

1. read(m)

2. read(n)

3. z = 0

4. m = m -n

5. z = z + 1

6. if m>= n goto 4

7. Write z

Page 25: Complete Report download programing

25

8. Halt

(c) m mod n

1. read(m)

2. read(n)

3. m = m -n

4. if m>= n goto 3

5. Write z

6. Halt

1.9- Under what conditions does the following RAM p rogram terminates?

1. read( M[1])

2. read(M[2])

3. M[1] := M[1] – M[2]

4. if M[1] >= 0 then goto 3

5. M[1] := M[1] + M[2]

6. writeln(M[1])

7. halt

Solution : M[2]> M[1]

1.10- Individual RAM instructions may be readable, but the limitations of the instruction set lead to convoluted programs. RAMs s upport conditionals of the form

If M[j] >= 0 then goto i

But not of either of the forms:

If M[j] = 0 then goto i

Page 26: Complete Report download programing

26

If M[j] = M[k] then goto i

The program below relies on those extensions to the RAM instruction set. Explain why: this program is equivalent to the program with in the RAM

1. M[0] := 0 2. Read( M[1]) 3. If M[1] = 0 then goto 9 4. Writeln( M[1]) 5. Read(M[2]) 6. If M[2] = M[1] then goto 5 7. M[1] := M[2] + M[3] 8. Goto 3 9. Halt

• For the program on page 6 • If Input = 112223144 • Output= 12314

• Also, for the given program in 1.10 • If Input = 112223144 • Output= 12314

Also, both the progams terminate when M[1]<=0

Thus, the two programs are equivalent.