Chapter 9Chapter 9
ProgrammingProgramming
LanguagesLanguages
2008-01-02_135642
Foundations of Computer Science Cengage Learning
1
 Describe the evolution of programming languages from machine     language to high-level languages.
 Understand how a program in a high-level language is translated     into machine language.
 Distinguish between four computer language paradigms.
 Understand the procedural paradigm and the interaction     between a program unit and data items in the paradigm.
 Understand the object-oriented paradigm and the interaction     between a program unit and objects in this paradigm.
 Define functional paradigm and understand its applications.
 Define a declaration paradigm and understand its applications.
 Define common concepts in procedural and object-oriented     languages.
ObjectivesObjectives
After studying this chapter, the student should be able to:After studying this chapter, the student should be able to:
2
9-1   EVOLUTION9-1   EVOLUTION
To write program for computer, we must use acomputer language. computer language is set ofpredefined words that are combined into programaccording to predefined rules (syntax). Over the years,computer languages have evolved from machinelanguage to high-level languages.To write program for computer, we must use acomputer language. computer language is set ofpredefined words that are combined into programaccording to predefined rules (syntax). Over the years,computer languages have evolved from machinelanguage to high-level languages.
3
Machine languages
In the earliest days of computers, the only programminglanguages available were machine languagesEach computerhad its own machine language, which was made of streamsof 0s and 1s. In Chapter we showed that in primitivehypothetical computer, we need to use eleven lines of codeto read two integers, add them and print the result. Theselines of code, when written in machine language, makeeleven lines of binary code, each of 16 bits, as shown inTable 9.1.
The only language understood by a computer is machinelanguage.
 i
4
5
Assembly languages
The next evolution in programming came with the idea ofreplacing binary code for instruction and addresses withsymbols or mnemonics. Because they used symbols, theselanguages were first known as symbolic languages. The setof these mnemonic languages were later referred to asassembly languages. The assembly language for ourhypothetical computer to replace the machine language inTable 9.2 is shown in Program 9.1.
The only language understood by a computer is machinelanguage.
 i
6
7
High-level languages
Although assembly languages greatly improvedprogramming efficiency, they still required programmers toconcentrate on the hardware they were using. Working withsymbolic languages was also very tedious, because eachmachine instruction had to be individually coded. The desireto improve programmer efficiency and to change the focusfrom the computer to the problem being solved led to thedevelopment of high-level languages.
Over the years, various languages, most notablyBASIC, COBOL, Pascal, Ada, C, C++ and Java, weredeveloped. Program 9.1 shows the code for adding twointegers as it would appear in the C++ language.
8
9
9-2   TRANSLATION9-2   TRANSLATION
Programs today are normally written in one of the high-level languages. To run the program on computer, theprogram needs to be translated into the machinelanguage of the computer on which it will run. Theprogram in high-level language is called the sourceprogram. The translated program in machine language iscalled the object program. Two methods are used fortranslation: compilation and interpretation.Programs today are normally written in one of the high-level languages. To run the program on computer, theprogram needs to be translated into the machinelanguage of the computer on which it will run. Theprogram in high-level language is called the sourceprogram. The translated program in machine language iscalled the object program. Two methods are used fortranslation: compilation and interpretation.
10
Compilation
compiler normally translates the whole source programinto the object program.
Interpretation
Some computer languages use an interpreter to translate thesource program into the object program. Interpretation refersto the process of translating each line of the source programinto the corresponding line of the object program andexecuting the line. However, we need to be aware of twotrends in interpretation: that used by some languages beforeJava and the interpretation used by Java.
11
12
First approach to interpretation
(such as Basic and APL) use a kind of interpretation process that eachline of the source program is translated into the machine language ofthe computer being used and executed immediately
Second approach to interpretation
(java) introduced anew kind of interpretation in which that thetranslation from source program to object program is done in two steps:compilation and interpretation
A java code is first compiled to create java bytecode, which looks likecode in machine language but not for any specific computer: it is objectcode for a virtual machine ,called the java virtual machine or JVM.
The byte code then compiled or interepted by any computer that runs aJVM emulator
Translation process
Compilation and interpretation differ in that the firsttranslates the whole source code before executing it, whilethe second translates and executes the source code line at atime. Both methods, however, follow the same translationprocess shown in Figure 9.1.
Figure 9.1  Source code translation process
13
9-3   PROGRAMMING PARADIGMS9-3   PROGRAMMING PARADIGMS
Today, computer languages are categorized according tothe approach they use to solve problem. paradigm,therefore, is way in which computer language looksat the problem to be solved. We divide computerlanguages into four paradigms: procedural, object-orientedfunctional and declarativeFigure 9.2summarizes these.Today, computer languages are categorized according tothe approach they use to solve problem. paradigm,therefore, is way in which computer language looksat the problem to be solved. We divide computerlanguages into four paradigms: procedural, object-orientedfunctional and declarativeFigure 9.2summarizes these.
14
Figure 9.2  Categories of programming languages
15
The procedural paradigm
In the procedural paradigm (or imperative paradigm) we canthink of program as an active agent that manipulatespassive objects. We encounter many passive objects in ourdaily life: stone, book, lamp, and so on. passiveobject cannot initiate an action by itself, but it can receiveactions from active agents.
program in procedural paradigm is an active agentthat uses passive objects that we refer to as data or dataitems. To manipulate piece of data, the active agent(program) issues an action, referred to as procedure. Forexample, think of program that prints the contents of file.The file is passive object. To print the file, the programuses procedure, which we call print.
16
Figure 9.3  The concept of the procedural paradigm
17
program in this paradigm is made up of three parts: partfor object creationset of procedure calls and set of codefor each procedureSome procedures have already beendefined in the language itself. By combining this code, theprogrammer can create new procedures.
Figure 9.4  The components of a procedural program
18
Some procedural languages
 FORTRAN (FORmula TRANslation)
 COBOL (COmmon Business-Oriented Language)
 Pascal
 C
 Ada
19
The object-oriented paradigm
The object-oriented paradigm deals with active objectsinstead of passive objects. We encounter many active objectsin our daily life: vehicle, an automatic door, dishwasherand so on. The action to be performed on these objects areincluded in the object: the objects need only to receive theappropriate stimulus from outside to perform one of theactions.
file in an object-oriented paradigm can be packedwith all the procedures—called methods in the object-oriented paradigm—to be performed by the file: printing,copying, deleting and so on. The program in this paradigmjust sends the corresponding request to the object.
20
Figure 9.5  The concept of an object-oriented paradigm
21
Classes
As Figure 9.5 shows, objects of the same type (files, forexample) need set of methods that show how an object ofthis type reacts to stimuli from outside the object’s“territories”. To create these methods, unit called class isused (see Appendix F).
Figure 9.6  The concept of an object-oriented paradigm
22
Methods
In general, the format of methods are very similar to thefunctions used in some procedural languages. Each methodhas its header, its local variables and its statement. Thismeans that most of the features we discussed for procedurallanguages are also applied to methods written for an object-oriented program. In other words, we can claim that object-oriented languages are actually an extension of procedurallanguages with some new ideas and some new features. TheC++ language, for example, is an object-oriented extensionof the language.
23
Inheritance
In the object-oriented paradigm, as in nature, an object caninherit from another object. This concept is calledinheritance. When general class is defined, we can define amore specific class that inherits some of the characteristics ofthe general class, but also has some new characteristics. Forexample, when an object of the type GeometricalShapes isdefined, we can define class called Rectangles. Rectanglesare geometrical shapes with additional characteristics.
24
Polymorphism
Polymorphism means “many forms”. Polymorphism in theobject-oriented paradigm means that we can define severaloperations with the same name that can do different things inrelated classes. For example, assume that we define twoclasses, Rectangles and Circles, both inherited from the classGeometricalShapes. We define two operations both namedarea, one in Rectangles and one in Circles, that calculate thearea of rectangle or circle. The two operations have thesame name
25
Some object-oriented languages
 C++
 Java
26
The functional paradigm
In the functional paradigm program is considered amathematical function. In this context, function is blackbox that maps list of inputs to list of outputs.
Figure 9.7  A function in a functional language
27
Some functional languages
 LISP (LISt Programming)
 Scheme
28
The declarative paradigm
declarative paradigm uses the principle of logicalreasoning to answer queries. It is based on formal logicdefined by Greek mathematicians and later developed into
first-order predicate calculus.
Logical reasoning is based on deduction. Somestatements (facts) are given that are assumed to be true, andthe logician uses solid rules of logical reasoning to deducenew statements (facts). For example, the famous rule ofdeduction in logic is:
29
9-4   COMMON CONCEPTS9-4   COMMON CONCEPTS
In this section we conduct quick navigation throughsome procedural languages to find common concepts.Some of these concepts are also available in mostobject-oriented languages because, as we explained, anobject-oriented paradigm uses the procedural paradigmwhen creating methods.In this section we conduct quick navigation throughsome procedural languages to find common concepts.Some of these concepts are also available in mostobject-oriented languages because, as we explained, anobject-oriented paradigm uses the procedural paradigmwhen creating methods.
30
Identifiers
One feature present in all procedural languages, as well as inother languages, is the identifier—that is, the name ofobjects. Identifiers allow us to name objects in the program.For example, each piece of data in computer is stored at aunique address. If there were no identifiers to represent datalocations symbolically, we would have to know and use dataaddresses to manipulate them. Instead, we simply give datanames and let the compiler keep track of where they arephysically located.
31
Data types
data type defines set of values and set of operationsthat can be applied to those values. The set of values for eachtype is known as the domain for the type. Most languagesdefine two categories of data types: simple types andcomposite types.
simple type is data type that cannot be broken intosmaller data types.
composite type is set of elements in which eachelement is simple type or composite type.
32
33
Simple data Types
1- An integer is a whole number withoutfractional part
2-A real type is a number with fractional part
3- A character type is a symbol in theunderlying character set used by language, forexample ,ASCII
4-Boolean type is type with only two values,”true “or “false”
Variables
Variables are names for memory locations. As discussed inChapter 5, each memory location in computer has anaddress. Although the addresses are used by the computerinternally, it is very inconvenient for the programmer to useaddresses. programmer can use variable, such as score,to store the integer value of score received in test. Since avariable holds data item, it has type.
34
35
Variable Declaration
Char C;
Int num;
Double result;
Variable initialization
Char C=‘Z’;
Int num=123;
Double result= 256,782;
Literals
literal is predetermined value used in program. Forexample, if we need to calculate the area of circle when thevalue of the radius is stored in the variable rwe can use theexpression 3.14 × r2in which the approximate value of π(pi) is used as literal. In most programming languages wecan have integer, real, character and Boolean literals. In mostlanguages, we can also have string literals. To distinguish thecharacter and string literals from the names of variables andother objects, most languages require that the characterliterals be enclosed in single quotes, such as 'A', and stringsto be enclosed in double quotes, such as "Anne".
36
Constants
     Most programming languages define constants. Aconstantlike variable, is named location that can store avalue, but the value cannot be changed after it has beendefined at the beginning of the program. However, if wewant to use the program later, we can change just one line atthe beginning of the program, the value of the constant.
37
Const Float tax= 256,782;
Cost=price*tax;
Inputs and Outputs
Almost every program needs to read and/or write data. Theseoperations can be quite complex, especially when we readand write large files. Most programming languages use apredefined function for input and output.
Data is input by either statement or predefinedfunction such as scanf in the language.
Data is output by either statement or predefinedfunction such as printf in the language.
38
Expressions
An expression is sequence of operands and operators thatreduces to single value. For example, the following is anexpression with value of 13:
An operator is language-specific token that requiresan action to be taken. The most familiar operators are drawnfrom mathematics.
39
Table 9.3 shows some arithmetic operators used in C, C++,and Java.
40
Relational operators compare data to see if value is greaterthan, less than, or equal to another value. The result ofapplying relational operators is Boolean value (true orfalse). C, C++ and Java use six relational operators, asshown in Table 9.4:
41
Logical operators combine Boolean values (true or false) toget new value. The language uses three logical operators,as shown in Table 9.5:
42
Statements
statement causes an action to be performed by theprogram. It translates directly into one or more executablecomputer instructions. For example, C, C++ and Java definemany types of statements.
An assignment statement assigns value to variable. Inother words, it stores the value in the variable, which hasalready been created in the declaration section.
compound statement is unit of code consisting of zero ormore statements. It is also known as block. compoundstatement allows group of statements to be treated as asingle entity.
43
Structured programming strongly recommends the use of thethree types of control statements: sequenceselection andrepetitionas we discussed in Chapter 8.
Figure 9.9  Two-way and multi-way decisions
44
Figure 9.10  Three types of repetition
45