Concept of Programming Languages – Chapter 16 (Logic Programming Languages)

Review Question
1. What are the three primary uses of symbolic logic in formal logic ?
– to express propositions, to express the relationships between propositions, and to
describe how new propositions can be inferred from other propositions that
are assumed to be true.

2. What are the two parts of a compound term ?
– functor and and ordered list of of parameters

3. What are the two modes in which a proposition can be stated ?
– one in which a proposition is defined to be true and one in which that the proposition is something to be determined.

4. What is general form of a proposition in clausal form ?
-B1 U B2 U . . . U Bn C A1 n A2 n . . . n Am

5. What are antecedents ? Consequents ?
– Antecedents are right side of a clausal form proposition. Consequent is left side of a clausal form propositions

6. Give general definitions of resolution and unification
– Resolution : inference rule that allows inferred propositions to be computed from given propositions, thus providing a method with potential application to automatic theorem proving.
Unification : Process of determining useful values for variables.

7. What are the forms of Horn clauses ?
– a. Have a single atomic proposition on the left side
b. empty left side.

9. What does it mean for a language to be nonprocedural ?
– Language in which the programs do not exactly state how a result is to be computed but rather describe the form of the result.

Problem Set
1. “All predicate calculus propositions can be algorithmically converted to clausal form”. Is this statement true or false ? Explain.
– True.

8. Critically comment on the following statement : “ Logic programs are nonprocedural”
– It is true, because logical programs use lots of different processes based on its conditions. If a certain logical requirement is true, then a program will execute the corresponding process, instead of procedurally executing the statements.

9. From a book on Prolog, learn and write a description of a monkey-banana prolem. Why does Prolog allow this problem to exist in its implementation ?
– The problem is defined as this : a monkey is in a room. Suspended from the ceiling is a bunch of bananas, beyond the monkey’s reach. However, in the room there are also a chair and a stick. The ceiling is just the right height so that a monkey standing on a chair could knock the bananas down with the stick. The monkey knows how to move around, carry other things around, reach for the bananas, and wave a stick in the air. What is the best sequence of actions for the monkey?
It exists to create a variation in output of Prolog. As Prolog is an AI programming language, a variation might be needed in AI output to make them respond relevant to the situation.

Concept of Programming Languages – Chapter 15 (Functional Programming Languages)

REVIEW QUESTION:

2. What does a lambda expression specify?
The predicate function is often given as a lambda expression, which in ML is defined exactly like a function, except with the fn reserved word, instead of fun, and of course the lambda expression is nameless.

5. Explain why QUOTE is needed for a parameter that is a data list.
To avoid evaluating a parameter, it is first given as a parameter to the primitive function QUOTE, which simply returns it without change.

6. What is a simple list?
A list which membership of a given atom in a given list that does not include sublists.

7. What does the abbreviation REPL stand for?
REPL stand for read-evaluate-print loop.

11. What are the two forms of DEFINE?
The simplest form of DEFINE is one used to bind a name to the value of an expression. This form is
(DEFINE symbol expression)
The general form of such a DEFINE is
(DEFINE (function_name parameters)
(expression)
)

13. Why are CAR and CDR so named?
The names of the CAR and CDR functions are peculiar at best. The origin of these names lies in the first implementation of LISP, which was on an IBM 704 computer. The 704’s memory words had two fields, named decrement and address, that were used in various operand addressing strategies. Each of
these fields could store a machine memory address. The 704 also included two machine instructions, also named CAR (contents of the address part of a register) and CDR (contents of the decrement part of a register), that extracted the associated fields. It was natural to use the two fields to store the two pointers
of a list node so that a memory word could neatly store a node. Using these conventions, the CAR and CDR instructions of the 704 provided efficient list selectors. The names carried over into the primitives of all dialects of LISP.

18. What is tail recursion? Why is it important to define functions that use recursion to specify repetition to be tail recursive?
A function is tail recursive if its recursive call is the last operation in the function. This means that the return value of the recursive call is the return value of the nonrecursive call to the function. It is important to specify repetition to be tail recursive because it is more efficient(increase the efficiency).

19. Why were imperative features added to most dialects of LISP?
LISP began as a pure functional language but soon acquired some important imperative features to increased its execution efficiency.

26. What is type inferencing, as used in ML?
Type inference refers to the automatic deduction of the type of an expression in a programming language. If some, but not all, type annotations are already present it is referred to as type reconstruction.

29. What is a curried function?
Curried functions a function which a new functions can be constructed from them by partial evaluation.

30. What does partial evaluation mean?
Partial evaluation means that the function is evaluated with actual parameters for one or more of the leftmost formal parameters.

32. What is the use of the evaluation environment table?
A table called the evaluation environment stores the names of all implicitly and explicitly declared identifiers in a program, along with their types. This is like a run-time symbol table.

33. Explain the process of currying.
The process of currying replaces a function with more than one parameter with a function with one parameter that returns a function that takes the other parameters of the initial function.

Problem Set
4. Refer to a book on Haskell programming and discuss the feature of Haskell.
– Haskell features lazy evaluation, pattern matching, list comprehension, type classes, and type polymorphism. It is a purely functional language, which means that in general, functions in Haskell do not have side effects. There is a distinct construct for representing side effects, orthogonal to the type of functions. A pure function may return a side effect which is subsequently executed, modeling the impure functions of other languages.
Haskell has a strong, static type system based on Hindley–Milner type inference. Haskell’s principal innovation in this area is to add type classes, which were originally conceived as a principled way to add overloading to the language, but have since found many more uses.
The construct which represents side effects is an example of a monad. Monads are a general framework which can model different kinds of computation, including error handling, nondeterminism, parsing, and software transactional memory. Monads are defined as ordinary datatypes, but Haskell provides some syntactic sugar for their use.

9. What does the following Scheme function do ?
(define (y s list)
(cond
((null? Lis) ‘ () )
((equal? S (car lis)) lis)
(else (y s (cdr lis)))
))
– y returns the given list with leading elements removed up to but not including the first occurrence of the first given parameter.

10. What does the following Scheme functions do ?
(define (x lis)
(cond
((null ? lis) 0)
((not (list? (car lis)))
(cond
((eq? (car lis) #) (x (cdr lis)))
(else (+ 1 (x (cdr lis))))))
(else (+ (x (car lis)) (x (cdr lis))))
– x returns the number of non-NIL atoms in the given list.

Concept of Programming Languages – Chapter 14 (Exception Handling and Event Handling)

REVIEW QUESTION:
1. Define exception, exception handler, raising an exception, disabling an exception, continuation, finalization, and built-in exception.

– Exception : any unusual event, erroneous or not, that is detectable by either hardware or software and that may require special processing.

Exception handler : a code unit which processes an exception.

Raising an exception : When a event associated with an exception occurs

Disabling an exception : Ignoring a certain hardware-detectable exceptions.

Continuation : Control transfer to somewhere in the program outside of the handler code or program might terminate .

Finalization : ability to complete some computation regardless of how subprogram execution terminates.

Built-in exception : Exception that is not made by the user, but rather comes as default.

2. When is an exception thrown or raised ?
– When an event associated with an exception occurs

3. What are the advantages of having support for exception handling built in to a language ?

– Without built-in exception handling, the code to detect error condition can be a clutter to the program. Existence of built-in exception handling would simplify a source program.

4. Give an example of hardware-detectable execution.

– Division by zero

5. What does it mean for an exception to be bound to an exception handler ?

– A specific exception is to be handled by a specific exception handler also, because different exceptions are to be treated differently.

6 . What is exception propagation in Ada?
Exception propagation allows an exception raised in one program unit to be handled in some other unit in its dynamic or static ancestry. This allows a single exception handler to be used for any number of different program units. This reuse can result in significant savings in development cost, program size, and program complexity.

9. What is the scope of exception handlers in Ada?
Exception handlers can be included in blocks or in the bodies of subprograms, packages, or tasks.

10. What are the four exceptions defined in the Standard package of Ada ?

– Constraint_Error,Program_Error,Storage_Error, and Tasking_Error.

11. Are there any predefined exceptions in Ada ?

– Yes, there are, for example Ada.Text_IO defines the End_Error exception.

12. What is the use of Suppress pragma in Ada ?
– Run-time checks that are parts of built-in exceptions can be disabled in Ada programs

13. Describe three problems with Ada’s exception handling.

– The propagation model, which allows exceptions to be propagated to an outer scope in which the exception is not visible, inadequacy of exception handling for tasks, and exception handling was not extended to deal with new constructs in Ada 95.

Problem Set
1. What mechanism did early programming languages provide to detect to attempt to deal with errors ?

– There were no possibility for the user program to detect or attempt to deal with errors. In case if error happens, the program will be terminated and control will be transferred to the operating system.

2. Describe the approach for the detection of subscript range errors used in C and Java.

– C does not check subscript ranges. While in Java, compilers usually generate a code to check the correctness of every subscript expression. If any exception generates, an unchecked exception is thrown.

6. In languages without exception-handling facilities, it is common to have most subprograms include an “error” parameter, which can be set to some values representing “OK” or some other value representing “error in procedure”. What advantage does a linguistic exception-handling facility like that of Ada have over this method?

– There are several advantages, for example in Ada, using an error flag parameter in all subprograms. One advantage is that the code to test the error is eliminated after every call. Such test code makes program longer and harder to read. Second advantage is that exceptions can be propagated farther in a uniform and implicit way. Also, there is an advantage that all program use a similar method to deal with exceptions, which enhances readability.

7. In a language without exception-handling facilities, we could send an error-handling procedure as a parameter to each procedure that can detect errors that must be handled. What disadvantages are there to this method ?

– There are several disadvantages of sending error handling subprograms to other subprograms. One is that it may be necessary to send several error handlers to some subprograms, greatly complicating both the writing and execution of calls. Another is that there is no method of propagating exceptions, meaning that they must all be handled locally. This complicates exception handling, because it requires more attention to handling in more places.

Concept of Programming Languages – Chapter 13 (Concurrency)

REVIEW QUESTION:

1. What are the three possible levels of concurrency in programs?

– Instruction level (executing two or more machine instructions simultaneously)

– Statement level (executing two or more high-level language statements simultaneously)

– Unit level (executing two or more subprogram units simultaneously)

7. What is the difference between physical and logical concurrency?

Physical concurrency is several program units from the same program that literally execute simultaneously.

Logical concurrency is multiple processors providing actual concurrency, when in fact the actual execution of programs is taking place in interleaved fashion on a single processor.

8. What is the work of a scheduler?

Scheduler manages the sharing of processors among the tasks.

12. What is a heavyweight task? What is a lightweight task?

Heavyweight task executes in its own address space. Lightweight task all run in the same address space.

16. What is a task descriptor?

Task descriptor is a data structure that stores all of the relevant information about the execution state of a task.

18. What is the purpose of a task-ready queue?

The purpose of a task-ready queue is to be storage of tasks that are ready to run.

21. What is a binary semaphore? What is a counting semaphore?

Binary semaphore is a semaphore that requires only a binary-valued counter, like the one used to provide competition synchronization. A counting semaphore is a synchronization object that can have an arbitrarily large number of states.

30. What is purpose of an Ada terminate clause?

The purpose of an Ada terminate clause is to mark that the task is finished with its job but is not yet terminated.

34. What does the Java sleep method do?

Sleep method blocks the the thread.

35. What does the Java yield method do?

Yield method surrenders the processor voluntarily as a request from the running thread.

36. What does the Java join method do?

Java forces a method to delay its execution until the run method of another thread has completed its execution.

37. What does the Java interrupt method do?

Interrupt becomes one way to communicate to a thread that it should stop.

55. What is Concurrent ML?

Concurrent ML is an extension to ML that includes a fform of threads and a form of synchronous message passing to support concurrency.

56. What is the use of the spawn primitive of CML?

The use of Spawn primitive of CML is to create a thread.

57. What is the use of subprograms BeginInvoke and EndInvoke in F#?

The use of subprograms BeginInvoke and Endinvoke in F# is to call threads asynchronously.

58. What is the use of the DISTRIBUTE and ALIGN specification of HPC?

The use of DISTRIBUTE and ALIGN specification of HPC is to provide information to the compiler on machines that do not share memory, that is, each processor has its own memory.

PROBLEM SET:

1. Explain clearly why a race condition can create problems for a system.

Because two or more tasks are racing to use the shared resource and the behavior of the program depends on which task arrives first (and wins the race). The importance of competition synchronization should now be clear.

2. What are the different ways to handle deadlock?

– Ignoring deadlock

– Detection

– Prevention

– Avoidance

3. Busy waiting is a method whereby a task waits for a given event by continuously checking for that event to occur. What is the main problem with this approach?

Busy-waiting or spinning is a technique in which a process repeatedly checks to see if a condition is true, such as whether keyboard input or a lock is available. Spinning can also be used to generate an arbitrary time delay, a technique that was necessary on systems that lacked a method of waiting a specific length of time. Processor speeds vary greatly from computer to computer, especially as some processors are designed to dynamically adjust speed based on external factors, such as the load on the operating system. Busy waiting may loop forever and it may cause a computer freezing.

Concept of Programming Languages – Chapter 12 (Support for Object-Oriented Programming)

REVIEW QUESTION:

2. What are the problems associated with programming using abstract data types?

-In nearly all cases, the features and capabilities of the existing type are not quite right for the new use.

-The type definitions are all independent and are at the same level.

4. What is message protocol?

Message protocol is the entire collection of methods of an object.

5. What is an overriding method?

Overriding method is method that overrides the inherited method.

7. What is dynamic dispatch?

Dynamic dispatch is the third characteristic (after abstract data types and inheritance) of object-oriented programming language which is a kind of polymorhphism provided by the dynamic binding of messages to method definitions.

12. From where are Smalltalk objects allocated?

Smalltalk objects are allocated from the heap and are referenced through reference variables, which are implicitly dereferenced.

15. What kind of inheritance, single or multiple, does Smalltalk support?

Smalltalk supports single inheritance; it does not allow multiple inheritance.

19. How are C++ heap-allocated objects deallocated?

C++ heap-allocated objects are deallocated using destructor.

29. Does Objective-C support multiple inheritance?

No Objective-C doesn’t support it. (It supports only single inheritance).

33. What is the purpose of an Objective-C category?

The purpose of an Objective-C category is to add certain functionalities to different classes and also to provide some of the benefits of multiple inheritance, without the naming collisions that could occur if modules did not require module names on their functions.

38. What is boxing?

Boxing is primitive values in Java 5.0+ which is implicitly coerced when they are put in object context. This coercion converts the primitive value to an object of the wrapper class of the primitive value’s type.

39. How are Java objects deallocated?

By implicitly calling a finaliz emethod when the garbage collector is about to reclaim the storage occupied by the object.

Problem Set

2. In what ways can “compatible “ be defined for the relationship between an overridden method and the overriding method ?
– in ways of its formal definition, the parameters and return types.

3. Compare the inheritance of C++ and Java.
– In Java, all objects are Inherited, either directly or indirectly. While in C++ a class can be defined to stand on its own without an ancestor.

– In Java, there’s no access level specifier of inheritance, while C++ has private public and protected.

– In Java, the functions are virtual by default. While in C++ the functions CAN BE MADE virtual with the keyword virtual

7. What is one programming situation where multiple inheritance has a significant disadvantage over interfaces ?
– When two or more parent classes are derived from one grandparent class and has one child. (diamond problem)

9. Given an example of inheritance in C++, where a subclass overrides the superclass methods.
– class human{
public :
void eat(){std::cout<<”Eating”;}
}
class man : public human{
public :
void eat(){std::cout<<”Eat like a boss”;}
}

10. Explain one advantage of inheritance
– Allows programmer to reuse a class with modifications that doesn’t apply to the initial class, so both class can still be used. This also improves readability and writability.

14. Explain type checking in Java
-Type checking happens before execution. Type checking can only uses type information that have declared in your program, and not the possible type that an object has at runtime. Java checks all line of code to make sure that it uses values correctly according to the declared types.

16. State why Java is said to be more pure object oriented than C++.
-Because Java implements pure class. Every function / statements in Java is run by a class. While in C++ not all functions are run by a class.

17. What are the different options for object destruction in Java ?
– Using Close method or Finalize method.

Concept of Programming Languages – Chapter 11 (Abstract Data Types and Encapsulation Constructs)

Review Questions

1. What are the two kinds of abstractions in programming languages ?

– Process Abstraction and Data Abstraction

2. Define abstract data type .

– A data structure in the form of a record, but which includes subprograms that manipulate its data.

3. What are the advantages of the two parts of the definition of abstract data type ?

– Increased reliability, Reduces range of code and number of variables which a programmer must be aware when writing / reading part of program. Make name conflict less likely to happen

5. What are the language design issues for abstract data types ?

– ADTs must have a function that allows a user to modify a value inside that data type. Although the method is public, the value itself must be private.

10. What is the use of the Ada with clause ?

– To make the names defined in external packages visible

11. What is the use of the Ada use clause ?

– To eliminate the need for explicit qualification of the references to entities from the named package.

12. What is the fundamental difference between a C++ class and an Ada package ?

– Class must be accessed from an instance of itself while package can be accessed directly.

13. From where are C++ objects allocated ?

– From heap

15. What is the purpose of a C++ destructor ?

– To deallocate heap space the object used.

16. What are the legal return types of a destructor ?

– destructor has no return type

21. What are initializers in Objective-C?

– Constructors that must be explicitly called.

26. Why does Java not have destructors ?

– Because Java has its own implicit garbage collection.

Problem Set

2. Suppose someone designed a stack abstract data type in which the function top returned an access path (or pointer ) rather than returning a copy of the top element. This is not a true data abstraction. Why ? Give an example that illustrates the problem.

– The problem with this is that the user is given access to the stack through the returned value of the “top” function. For example, if p is a pointer to objects of the type stored in the stack, we could have:

p = top(stack1);

*p = 42;

These statements access the stack directly, which violates the principle of a data abstraction.

4. What are the advantages of the nonpointer concept in Java ?

– Variable Access are absolutely defined by the programmer

– No memory leak (i.e. dangling pointers, nameless variables etc)

9. What happens if the constructor is absent in Java and C++ ?
– The compiler will automatically make a default one

11. Why is the destructor of C# rarely used ?
– Because C# has its own garbage collection method , just like Java

Concepts of Programming Languages – Chapter 10 (Implementing Subprograms)

REVIEW QUESTION:

1. What are the two reasons why implementing subprograms with stack-dynamic local variables is more difficult than implementing simple sub-programs?

A stack-dynamic local variable is more complex activation records. The compiler must generate code to cause implicit allocation and de-allocation of local variables
Recursion must be supported (adds the possibility of multiple simultaneous activations of a subprogram).

2. What is the difference between an activation record and activation record instance?

The Format, or layout, of the non-code part of a subprogram is called an activation record.

An activation record stores all the information about subprogram calls, activation records stores the following data (in the following order)

Return address
Static link – to the static parent (where the subprogram is declared).
Dynamic link – to the caller of this subprogram.
Parameters
Local variables.

4. What are the two steps in locating a nonlocal variable in a static-scoped language with stack-dynamic local variables and nested subprograms?

Find the correct activation record instance
Determine the correct offset within that activation record instance

5. Define static chain, static depth, nesting_depth, and chain offset.

A static chain is a chain of static links that connects certain activation record instances

Static_depth is an integer associated with a static scope representing the scope’s nesting depth

The chain_offset or nesting_depth of a non-local reference is the difference between the static_depth of the reference and that of the scope where it is declared

6. What are the two potential problems with the static chain methods?

A nonlocal reference is slow if the number of scopes between the reference and the declaration of the referenced variable is large
Time-critical code is difficult, because the costs of nonlocal references are not equal, and can change with code upgrades and fixes

7. What is display?

One alternative to static chain is to use a display, for this approach, the static links are collected in a single array called a display. Display uses a pointer array to store the activation records along the static chain.

10. Explain the two methods of implementing block?

Blocks are treated as parameter less subprograms that are always called from the same place in the program.

Block can also be implemented in a different and somewhat simpler and more efficient way. The maximum amount of storage required for block variables at any time during the exaction of program can be statically determined, because block are entered and exited in strictly textual order.

11. Describe the deep access method of implementing dynamic scoping?

Deep Access – nonlocal references are found by searching the activation record instances on the dynamic chain. Length of chain cannot be statically determined every activation record instance must have variable names

12. Describe the shallow access method of implementing dynamic scoping?

In case of shallow access names and values are stored in a global table. Using this method, space is allocated for every variable name that is in the program (one space for variable temp though there might be several declarations of temp in the different methods). When a sub-routine is called it saves the current value of the variable and replaces it with the value in its current scope and restores the value of the variable while exiting.

14. Compare the efficiency of the deep access method to that of the shallow access method, in term of both call and nonlocal access?

The deep access methods provides fast subprogram linkage, but references to nonlocal, especially references to distant nonlocals (in term of the call chain), are costly. The shallow access methods provide much faster references to nonlocals, especially distant nonlocals, but are more costly in term of subprogram linkage.

Problem Set

6. Although local variables in Java methods are dynamically allocated at the beginning of each activation, under what circumstances could the value of a local variable in a particular activation retain the value of previous activation ?

– If the variable is declared as static. Static modifier is a modifier that makes a variable history – sensitive.

7. It is stated in this chapter that when nonlocal variables are accessed in a dynamic-scoped language using the dynamic chain, variable names must be stored in the activation records with the values. If this were actually done, every nonlocal access would require a sequence of costly string comparisons on names. Design an alternative to these string comparisons that would be faster.

– Using approach that uses an auxiliary data structure called a display. Or, to write variable names as integers. These integers act like an array. So when the activation happens, the comparisons will be faster.

9. The static-chain method could be expanded slightly by using two static links in each activation record instance where the second points to the static grandparent activation record instance. How would this approach affect the time required for subprogram linkage and nonlocal references ?

-Including two static links would reduce the access time to nonlocals that are defined in scopes two steps away to be equal to that for nonlocals that are one step away. Overall, because most nonlocal references are relatively close, this could significantly increase the execution efficiency of many programs.

11. If a compiler uses the static chain approach to implementing blocks, which of the entries in the activation records for subprograms are needed in the activation records for blocks?

There are two options for implementing blocks as parameterless subprograms: One way is to use the same activation record as a subprogram that has no parameters. This is the most simple way, because accesses to block variables will be exactly like accesses to local variables. Of course, the space for the static and dynamic links and the return address will be wasted. The alternative is to leave out the static and dynamic links and the return address, which saves space but makes accesses to block variables different from subprogram locals.

Concepts of Programming Languages – Chapter 9 (Subprograms)

REVIEW QUESTION:

1. What are the three general characteristics of subprograms?

– Each subprogram has a single entry point, excluding co-routine.
– The calling program is suspended during the execution of the called subprogram, which implies that there is only one subprogram in execution at any given time.
– Control always returns to the caller when the subprogram execution terminates.

4. What are formal parameters? What are actual parameters?

The parameters in the subprogram header are called formal parameters. Subprogram call statements must include the name of the subprogram and alist of parameters to be bound to the formal parameters of the subprogram. These parameters are called actual parameters.

5. What are the advantages and disadvantages of keyword parameters?

The advantage of keyword parameter is that they can appear in any order in the actual parameter list.
The disadvantage to keyword parameters is that the user of the subprogram must know the names of formal parameters.

6. What are the design issues for subprograms?

– What parameter-passing method or methods are used?
– Are the types of the actual parameters checked against the types of the formal parameters?
– Are local variable statically or dynamically allocated?
– Can subprogram definitions appear in other subprogram definitions?
– If subprograms can be passed as parameters and subprograms can be nested, what is the referencing environment of a passed subprogram?
– Can a subprogram be overloaded?
– Can subprograms be generic?

7. What are the advantages and disadvantages of dynamic local variables?

Advantages:

– They provide flexibility to the subprogram
– The storage of local variables in an active subprogram can be shared with the local variables in all inactive subprograms.
– They efficiently used when computer has small memory (Faster Access).

Disadvantages:

– Cost of the time required to allocate
– Access to dynamic local variable must be indirect
– The stack dynamic local variables, subprograms cannot be history sensitive

9. What are the modes, the conceptual modes of transfer, the advantages, and the disadvantages or pass-by-value, pass-by-result, pass-by-value-result, and pass-by-reference parameter-passing models?

There are two conceptual models of how data transfers take place in parameter transmission. Either an actual value is copied or an access path is transmitted.

The advantage of pass-by-value is its speed.

The Disadvantages of pass-by-value are, when copies are used, additional storage is required.

Storage and copy operations can be costly.

Pass-by-result has all of the advantages and disadvantages of pass-by-value, but more disadvantages. An additional disadvantage is that there can be an actual parameter collision, because order of expressions matter.

Pass-by-value-result has the same advantages and disadvantages as pass-by-value and pass-by-result with some more advantages. The largest extra advantage of pass-by-value-result is that it solves pass-by-reference’s aliasing problems.

An advantage of pass-by-reference is that it is efficient in both time and space.

A disadvantage to pass-by-reference is the increase in time to access formal parameters because of the additional level of indirect addressing. Secondly, if only one way communication to the called subprogram is required, inadvertent and erroneous changes may be made to the actual parameter. Finally, aliasing should be expected with pass-by-reference. Since pass-by-reference makes access paths available to the called subprograms, it broadens their access to nonlocal variables. These aliasing problems lead to decreased readability and reliability.

10. In what ways can aliases occur with pass-by-reference parameters?

Aliases can be occurring because pass-by-reference makes access paths available to the called subprograms.

17. What is parametric polymorphism?

Parametric polymorphism is provided by a subprogram that takes a generic parameter that is used in a type expression that describes the types of the parameters of the subprogram. Both Ada and C++ provides a kind of compile-time parametric polymorphism.

18. What causes a C++ template function to be instantiated?

C++ template functions are instantiated implicitly either when the function is named in a call or when its address is taken with the & processor.

19. In what fundamental way do the generic parameters to a Java 5.0 generic method differ from those of C++ methods?

Java does not use objects exclusively, java have no enumeration or record type. Whereas C++ Classes can be defined to have no parent, that is not possible in Java. All Java Classes must be subclass of the root class.

20. If a Java 5.0 method returns a generic type, what type of object is actually returned?

In Java any type or class can be returned by methods. Because methods are not types, they cannot be returned.

22. What are the design issues for functions?

Two design issues are functions.

Are side effects allowed?
What types of values can be returned?

23. In what ways are coroutines different from conventional subprogram?

Conventional subprograms are subordinate to their callers. When a routine calls a subprogram, execution suspends at that point in the program and resumes after the subprogram has run to completion. As a result, conventional subprogram invocation is atomic, much like a built-in statement in the programming language.

Problem Set
1. What are arguments for and against a user program building additional definitions for existing operators, as can be done in Python and C++? Do you think such user-defined operator overloading is good or bad ? Support your answer.
– It is good, as long as the user knows what he or she is doing. C++ default operators are only working for default data types. As users can make their own datatypes, custom operators are also needed.

3. Argue in support of the templated functions of C++. How is it different from the templated functions of other languages ?
– It is different as C++ differentiates function based on overloading. It is not practical to make multiple function overloading in regard to writability and readability. Instead, creating a template allows a function to receive any datatype as long as the variation is based on the formal parameter definition.

5. Consider the following program written in C syntax :
(page 458)
For each of the following parameter-passing methods, what are all of the values of the variables value and list after each of the three calls to swap ?
a. Passed by Value
-value =1 , list[5] = {2,4,6,8,10}
b. Passed by reference
-value =6, list[5] ={4,1,2,8,10}
c. Passed by value-result
-value =6, list[5] ={4,1,2,8,10}

7. Consider the following program written in C syntax :
(page 459)
For each of the following parameter-passing methods, what are the values of the list array after execution ?
a. Passed by value
– list[2] = {3,5}
b. Passed by reference
– list[2] = {6,10 }
c. Passed by value-result
– list[2] = {6,10 }

Concepts of Programming Languages – Chapter 8 (Statement-Level Control Structures)

REVIEW QUESTION:

1. What is the definition of control structure?

A control structure is a control statement and the collection of statements whose execution it controls.

2. What did Bohm and Jocopini prove about flowcharts?

It was proven that all algorithms that can be expressed by flowcharts can be coded in a programming languages with only two control statements: one for choosing between two control flow paths and one for logically controlled iterations.

3. What is the definition of block?

In Ruby, block is a sequence of code, delimited by either breves or the do and and reserved words.

4. What is/are the design issue(s) for all selection and iteration control statements?

There is only one design issue that is relevant to all of the selection and iteration control statements: Should the control structure have multiple entries?

7. Under what circumstances must an F# selector have an else clause?

An F# selector have an “else” clause if the “if” expression does return a value.

9. What are the design issues for multiple-selection statements?

– What is the form and type of the expression that controls the selection?
– How are the selectable segments specified?
– How are the case values specified?
– How should unrepresented selector expression values be handled, if at all?
– Is execution flow through the structure restricted to include just a single selectable segment?

14. What are the design issues for all iterative control statements?

– How is the iteration controlled?
– Where should the control mechanism appear in the loop statement?

15. What are the design issues for counter-controlled loop statements?

What are the type and scope of the loop variable?
– Should it be legal for the loop variable or loop parameters to be changed in the loop, and if so, does the change affect loop control?
– Should the loop parameters be evaluated only once, or once for every iteration?

21. What are the design issues for logically controlled loop statements?

– Should the control be pretest or post-test?
– Should the logically controlled loop be a special form of a counting loop or a separate statement?

23. What are the design issues for user-located loop control mechanisms?

– Should the conditional mechanism be an integral part of the exit?
– Should only one loop body be exited, or can enclosing loops also be exited?

Problem Set
1. What design issues should be considered for two-way selection statements ?
-What is the form and type of the expression that controls the selection ?
-How are the then and else clauses specified ?
-How should the meaning of nested selectors be specified ?

2.Python uses indentation to specify compound statements. Give an example in support of this statement.
Example :
if x > y :
x = y
print “case 1″

6. In C language, a control statement can be implemented using a nested if else, as well as by using a switch statement. Make a list of differences in the implementation of a nested if else and a switch statement. Also suggest under what circumstances the if else control structure is used and in which condition the switch case is used.
– Switch
• switch is usually more compact than lots of nested if else and therefore, more readable
• In many languages, switch only accepts only some data types.
if-else
• if allows complex expressions in the condition while switch wants a constant
• it accepts all data types
The if-else statement is used, in case if the programmer wants to the program to check whether a condition is true while the program is running, for example if the programmer wants to check whether a variable’s value is larger or smaller than x, he can use the if(var>x){stmts}.
The switch statements are usually used if the outcome of conditions are already known. For example ,in a menu input switch statement, the options are limited to either ‘Y’ or an ‘N’. Or numbered options. Using switch statement would allow the programmer to code with better readability than usign if-else statement.

14. State one of the main legitimate needs for gotos.
It is useful for programmer who wants to check errors in their program. Rather than fully modifying their code, they can put some goto statement inside the if statement and return the value of the error in case if an error happens.

Concepts of Programming Language – Chapter 7 ( Expressions and Assignment Statements)

Review Questions

1. Define operator precedence and operator associativity.

    operator precedence -> the value of an expression depends at least in part on the order of evaluation of the operators in the expression. the rules partially define the order in which the operators of different precedence levels are evaluated and  rules for expressions are based on the hierarchy of operator priorities.

    operator associativity -> an operator can have either left or right associativity, meaning that when there are 2 adjacent operators with the same precedence, the left operator is evaluated first or the right operator is evaluated first, respectively.

2.    What is a ternary operator?

        ternary operator is an operator with three operands.
 
 3.    What is a prefix operator?

          A prefix operator is an operator that precede their operands

 
 9.    What is a coercion?
        A coercion is the implicit type convertion.
 
10. What is a conditional expression?
      Conditional expression is a statement that uses if-then-else statements.
 
11. What is an overloaded operator?
      An overloaded operator is the multiple uses of an operator.
 
15. What is referential transparency?
      Referential transparency is two expressions in the program that have the same value can be substituted for one another anywhere in the program without affecting the action of the program.
 
Problem Set
3.    Do you think the elimination of overloaded operators in your favorite language would be beneficial? Why or why not?

it is not beneficial because it can be ambigious if we want to use that operator with the same type.
 
 
5.    Should C’s assigning operations (for example, +=) be included in other languages (that do not already have them)? Why or why not?
Yes, because we can make the operator simpler than before. We can just write a+=b instead a=a+b.
 
20.  Consider the following C program:
             int fun(int *i) {
                    *i += 5;
                      return 4;
              }
             void main() {
                      int x = 3;
                      x = x + fun(&x);
               }
 
What is the value of x after the assignment statement in main, assuming
a. operands are evaluated left to right.
b. operands are evaluated right to left.
 
a. 12
b. 7
 
21. Why does Java specify that operands in expressions are all evaluated in left-to-right order?
Java specify that operands in expressions are all evaluated in left-to-right order because Java is an associative language because associative in common language is evaluated from left to right.

Concepts of Programming Language – Chapter 6 (Data Types)

Review Question

1. What is a descriptor?

    descriptor -> the collection of the attributes of at variable. In an implementation, it is an area                            of memory that stores the attributes of a variable.

2. What are the advantages and disadvantages of decimal data types?

    advantages :

    – is able to precisely store decimal values, at least those within a restricted range that cannot be done with floating-point. (0.1 (in decimal) can be exactly represented in a decimal type, but not floating point type)

    disadvantages :

    – the range of values is restricted because no exponents are allowed, their representation in memory is mildly wasteful.

3. What are the design issues for character string types?

    – should string be simply a special kind of character array or a primitive type?

    – Should strings have static or dynamic length?

5. Define ordinal, enumeration, and subrange types.

    – ordinal ->one in which the range of possible values can be easily associated with the set                       of positive integers such as in Java, the primitive ordinal types are integer, char,                       and boolean.

    – enumeration -> one in which all of the possible values, which are named constants, are                                  provided, or enumerated, in the definition. It provides a way of defining                                      and grouping collections of named constants (enumeration constants)

9. Define static, fixed stack dynamic, stack-dynamic, fixed heap dynamic, and heap         dynamic arrays. What are the advantages of each?

    – Static array -> the subscript ranges that are statically bound and storage allocation is                                    static (done before run time). The advantage is efficiency, means that                                        there is no dynamic allocation or deallocation required.

    – Fixed Stack-dynamic array -> the subscript ranges that are statically bound, but the                                                              allocation is done at declaration elaboration time during                                                              execution. The advantage is space efficiency, means that                                                          a large array in one subprogram can use the same space                                                          as a large array in a different subprogram, as long as both                                                          subprograms are not active at the same time.

    – Stack-dynamic array -> both the subscript ranges and the storage allocation are                                                            dynamically bound at elaboration time. the advantage is                                                            flexibility. the size of an array need not be known until the array                                                is about to be used.

    – Fixed heap-dynamic array -> similar to a fixed stack dynamic array, in that the subscript                                                         ranges and the storage binding are both fixed after                                                                     storage is allocated. the differences are that both the                                                                 subscript ranges and storage bindings are done when the                                                         user program requests them during execution, and the                                                             storage is allocated from the heap, rather than the stack.                                                         the advantage is flexibility – the array’s size always fits the                                                         problem.

    – Heap dynamic array -> the binding of subscript ranges and storage allocation is dynamic                                               and can change any number of times during the array’s lifetime.                                               The advantage is flexibility, means that arrays can grow and                                                       shrink during program execution as the need for space changes.

12. What languages support negative subscripts?
     Perl language supports negative subscripts.
15. What is an aggregate constant?
     Aggregate constant is the parenthesized lists of values in Fortran language.
 
17. Define row major order and column major order.
      In Row major order is the elements of the array that have as their first subscript the lower       bound value of that subscript are stored first, followed by the elements of the second        value of the first subscript, and so forth. In column major order, the elements of an array that have as their last subscript the lower bound value of that subscript are stored first, followed by the elements of the second value of the last subscript, and so forth.
 
43.  What is a compatible type?
     compatible type is one that either is legal for the operator or is allowed under language rules to be implicitly converted by compiler-generated code (or the interpreter) to a legal type.
 
50. What is name type equivalence?
     Name type equivalence means that two variables have equivalent types if they are defined either in the same declaration or in declarations that use the same type name.
 
51. What is structure type equivalence?
      Structure type equivalence means that two variables have equivalent types if their types    have identical structures.
 
52.  What is the primary advantage of name type equivalence?
       The primary advantage of name type equivalence is easy to implement.
 
53. What is the primary disadvantage to structure type equivalence?
     The primary disadvantage to structure type equivalence is difficult to implement.
 
Problem Set

2.    How are negative integers stored in memory?

       A negative integer could be stored in sign-magnitude notation, in which the sign bit is set to indicate negative and the remainder of the bit string represents the absolute value of the number.

 

7.    Compare the pointer and reference type variable in C++.

       C++ pointers can point at any variable, regardless of where it is allocated. A C++ reference type variable is a constant pointer that is always implicitly dereferenced.

 

8.    What are the differences between the reference type variable in C++ and those of Java?

       C++ reference type variable is a constant, it must be initialized with the address of some variable in it definition, and after initialization a reference type variable can never be set to reference any other variable, besides Java reference variables can be assigned to refer to different class instances, they are not constants.

 

9.    C provides two derived data types both for name and structure type equivalence: struct and union. Make a study on when to use struct type variables and union type variables.

       With a union, we’re only supposed to use one of the elements, because they’re all stored at the same spot. This makes it useful when we want to store something that could be one of several types. A struct, on the other hand, has a separate memory location for each of its elements and they all can be used at once.

 

21. In what way is dynamic type checking better than static type checking?

       Dynamic type checking better than static type checking is when we want to provide more programming flexibility.

Concepts of Programming Language – Chapter 5 (Names, Bindings, Scopes)

Review Question

1. What are the design issues for names?

    – Are names case sensitive?

   – Are the special words of the language reserved words or keywords?

2. What is the potential danger of case-sensitive ?

   if the variables have the similar meanings, such as, “Rose” with “rose”, in case-sensitive,    there is no connection between them, case-sensitive violates the design principle that    language constructs that look similar should have similar meanings.

7. define binding and binding time.

   binding -> an association between an attribute and an entity, such as between a variable                      and its type or value, or between an operation and a symbol. Binding can take                      place at language design time, or run time.

   binding time -> the time at which a binding takes place.

13. Define lifetime, scope, static scope, and dynamic scope.

   lifetime -> the time during which the variables is bound to a specific memory location.

   scope -> the range of statements in which the variable is visible.

   static scope -> the scope of a variable can be statically determined – that is, prior to                              execution. it permits a human program reader and also a compiler to                              determine the type of every variable in the program simply by examining its                              source code.

   dynamic scope -> based on the calling sequence of subprograms, not on their spatial                                    relationship to each other, the scope can be determined only at run                                    time.

18. What is a block?

   A block is a section of code that allows to have its own local variables whose scope is    minimized and the variables are typically stack dynamic. Blocks provide the origin of the    phrase block-structured language.

19. What is the purpose of the let constructs in functional languages?

   This let constructs have two parts, which is to bind names to values, usually specified as    expressions and also an expression that uses the names defined in the bind names, rather    than statements.

Problem Set

  1. Decide which of the following identifier names is valid in C language. Support your decision.
_Student
int
Student
123Student
Student123
The valid identifiers are: _Student, Student, and Student123. It’s because an identifier in C language has its own rule. There are:
             – An identifier can’t be started with number. The number is valid as long as it is not in the front of an identifier.
               – An identifier can’t include any data types.
               – An identifier can’t be started with symbol.
               – There are not allowed if the name of identifiers if same.
 
 4.  Why is the type declaration of a variable necessary? What is the value range of the int type variable in Java?
The type declaration of a variable is necessary because, in a program it documented information about its data, which provides clues about the program’s behavior. The value range of the int type variable in Java is 32 bits (4 bytes).
 
10. Consider the following C program:
void fun(void) {
int a, b, c; /* definition 1 */
. . .
while (. . .) {
int b, c, d; /*definition 2 */

. . . <-1 p=””>

while (. . .) {
int c, d, e; /* definition 3 */

. . . <-2 p=””>

}

. . . <-3 p=””>

}

. . . <-4 p=””>

}
For each of the four marked points in this function, list each visible variable, along with the number of the definition statement that defines it.
– In 1 and 3 : the visible variables are a, b(both), c(both), and d from definition 1 and 2.
– In 2: the visible variables are a, b(both), c(both), d(both), and e from definition 1, 2, and 3.
– In 4: the visible variables are a, b, and c from the definition.

 

Concepts of Programming Language – Chapter 3 (Describing Syntax and Semantics)

Review Questions

1. Define Syntax and Semantics.

Syntax is the set of rules which define the combinations of symbols that are considered to be correctly structured programs in that language, it defines its surface form.

Semantics is the field concerned with the accurate mathematical study of the meaning of programming languages that evaluating the meaning of syntactically legal strings defined by a specific programming language, showing the computation involved.

2. Who are language descriptions for?

3. Describe the operation of a general language generator?

4. Describe the operation of a general language recognizer?

5. What is the difference between a sentence and a sentential form?

6. Define a left-recursive grammar rule.

7. What three extensions are common to most EBNFs?

8. Distinguish between static and dynamic semantics.

9. What purpose do predicates serve in an attribute grammar?

10. What is the difference between a synthesized and an inherited attribute?

11. How is the order of evaluation of attributes determined for the trees of a given attribute grammar?

12. What is the primary use of attribute grammars?

13. Explain the primary uses of methodology and notation for describing the semantics of programming languages.

14. Why can machine languages not to be used to define statements in operational semantics?

15. Describe the two levels of uses of operational semantics.

16. In denotational semantics, what are the syntactic and semantic domains?

17. What is stored in the state of a program for denotational semantics?

18. Which semantics approach is most widely known?

19. What two things must be defined for each language entity in order to construct a denotational description of the language?

20. Which part of an inference rule is the antecedent?

21. When is a grammar rule said to be left recursive?

22. Give an example of an ambiguous grammar.

23. On what branch of mathematics is axiomatic semantics based?

24. Give an unambiguous grammar for ifthen-else.

25. What is the problem with using a software pure interpreter for operational semantics?

26. Explain what the preconditions and postconditions of a given statement mean in axiomatic semantics.

27. What is loop invariant? Explain with an example.

28. What is the use of the wp function? Why it is called a predicate transformer?

29. Give the difference between total correctness and partial correctness.

Problem Set

1. Syntax error and semantic error are two types of compilation error. Explain the difference between the two in a program with examples.

2. Write EBNF descriptions for the following :

a. A Java class definition header statement.

b. A Java method call statement.

c. A C switch statement.

d. A C union definition.

e. C float literals.

3. Rewrite the BNF of Example 3.4 to represent operator – and operator / instead of operator + and operator *.

4. Rewrite the BNF of Example 3.4 to add the += and *= operators of Java.

5. Write a BNF description of relational operator of Java, including the two operators == and !=.

6. Using the grammar in Example 3.2, show a parse tree for each of the following statements :

a. A = A * (B * (C + A))

b. B = C * (A + C * B)

c. A = A + (B * (C))

7.Using the grammar in Example 3.4, show a parse tree for each of the following statements :

a. A = (A * B) + C

b. A = B * C + A

c. A = A + (B * C)

d. A = B * (C + (A * B))

8. Prove that the following grammar is ambiguous:

<S> -> <A>

<A> -> <A> * <A> | <id>

<id> x | y | z

9. Modify the grammar of example 3.4 to add a unary minus operator that has higher precedence than either + or *.

10. Describe, in English, the language defined by the following grammar :

<S> -> <X><Y>

<X> -> x<X> | x

<Y> -> y<Y> | y

Concept of Programming Language 2 (Evolution of the Major Programming Language)

REVIEW QUESTION

1. In what year was Plankalkul designed? In what year was that design published?

Plankalkul was designed by Konrad Zuse between 1942 & 1945. He first published a paper on it in 1948. More information on the language was published in 1972.

2. Mention an intereseting feature of Zuse’s programs.

One of the interesting feature of Zuse’s programs is the inclusion of mathematical expressions showing the current relationships between program variables.

3. What does Plankalkul mean?

Plankalkul means program calculus.

4. Speedcoding was invented to overcome two significant shortcomings of the computer hardware of the early 1950s. What were they ?

The first hardware shortcoming was the lack of floating point hardware. The second was the lack was automatic incrementing address registers.

5. What is the number of bits in a single word of the UNIVAC I’s memory? How are the bits grouped?

The number of bits is 72. It is grouped into 12 parts which contains 6 bit bytes each.

6. What hardware capability that first appeared in the IBM 704 computer strongly affected the evolution of programming languages ? Explain why.

Its capabilities prompted the development of Fortran because it was able to support floating-point operations hardware.

7. Who developed the Speedcoding system for the IBM 701 ?

The speedcoding was developed by John Backus.

8. Who developed Short Code? Why is Short Code called automatic programming?

The shortcode was developed by John Mauchly in 1949. Short Code is called automatic programming because Short Code was not
translated to machine code, it was implemented with a pure interpreter.

10. What was the most significant feature added to Fortran I to get Fortran II?

Independent-compilation capability

11. What control flow statements were added to Fortran IV to get Fortran 77?

logical loop statements and IF with an optional ELSE

12. Which version of Fortran was the first to have any sort of dynamic variables?

Fortran 90

13. Which version of Fortran was the first to have character string handling?

Fortran 77

14. Why were linguists interested in artificial intelligence in the late 1950s?

Linguists were concerned with natural language processing.

15. What are the different data types and structures in Common LISP?

Common LISP has a large number of data types and structures, including records, arrays, complex number, and character strings. It also has a form of packages for modularizing collection of function and data providing access control.

16. In what way are scheme and Common LISP opposites of each other?

Common LISP allows for static scoping and dynamic scoping Scheme only uses static scoping. Scheme is relatively small while Common LISP is large and complex.

17. What dialect of LISP is used for introductory programming courses at some universities?

Scheme

18. What two professional organizations together designed ALGOL 60?

ACM and GAMM

19. What was the goal for developing C?

C has adequate control statements and data-sructuring facilities to allow its use in many application areas. It alse has a rich set of operators that provide a high degree of expressiveness.

20. What were the significant modifications to ALGOL 58 to produce ALGOL 60?

The concept of block structure was introduced, two different means of passing parameters to subprograms were allowed, procedures were allowed to be recursive, stack-dynamic arrays were allowed.

21. What language was designed to describe the syntax of ALGOL 60?

BNF

22. On what language was COBOL based?

FLOW-MATIC

23. In what year did the COBOL design process begin?

1959

24. What data structure that appeared in COBOL originated with Plankalkul?

Hierarchical data structures (records)

25. What organization was most responsible for the early success of COBOL (in terms of extent of use)?

Department of Defense (DoD)

27. Why was BASIC an important language in the early 1980s?

Its smaller dialects could be implemented on computers with very small memories

28. PL/I was designed to replace what two languages?

COBOL and Fortran

29. For what new line of computers was PL/I designed?

the IBM system/360 line of computers

30. What features of SIMULA 67 are now important parts of some object-oriented languages?

Data abstraction

31. What innovation of data structuring was introduced in ALGOL 68 but is often credited to Pascal?

User-defined data types

32. What design criterion was used extensively in ALGOL 68?

Orthogonality

33. What language introduced the case statement?

The case statement was introduced in ALGOL-W, a version of ALGOL 60 created by Niklaus Wirth and C. A. R. (Tony) Hoare.

34. What operators in C were modeled on similar operators in ALGOL 68?

for and switch statements, in its assigning operators, and in its treatment of pointer

35. What are two characteristics of C that make it less safe than Pascal?

Lack of complete type checking and flexibility

37. What are the two kinds of statements that populate a Prolog database?

The statements that populate a Prolog database are called facts and rules.

38. What is the primary application area for which Ada was designed?

Embedded systems

39. What are the concurrent program units of ada called?

tasks (using the rendezvous mechanism)

42. What three concepts are the basis for object-oriented programming

Classes, objects and methods

43. Why does C++ include the features of Ada that are known to be unsafe?
A goal of Ada was that it could be used for which Ada could be used, so virtually none of the features of Ada would be removed, not even those considered to be unsafe.

44. From what language does Objective-C borrow its syntax for method calls?
Smalltalk language.

45. What programming paradigm that nearly all recently designed languages support is not supported by Go?
Doesn’t support traditional object-oriented programming, as it has no form of inheritance.

PROBLEM SET

1. What features of Fortran IV do you think would have had the greatest influence on Javaif the Java designers had been familiar with Fortran?
 Logical data type – boolean, used mainly for the control expressions of itscontrol statements (such as if and while).We can create simple version of the complex compile, and link processes of earlier compilers.
2. Determine the capabilities of Short Code, and compare them with those of a contemporary programmable hand calculator.
Short Code is capable of making multiplication without multiplication code needed, just put two operands side-by-side.Besides, it also uses pure interpreter to run itself.Short Code consists of coded version of mathematical expression that was to be evaluated.Contemporary programmable calculator was able to do multiplication with its embedded programming language. People can solve arithmetic problem easier than using the Short Code but it is more difficult to do further improvement to the programmable hand calculator than to the Sort Code.

3. Write a short history of Fortran 0, Fortran I, Fortran II and Fortran IV systems.

Fortran 0
– Fortran 0 was described in the IBM report titled “The IBM Mathematical FORmula TRANslating System : FORTRAN”. It was boldly stated that FORTRAN would provide the efficiency of hand-coded programs and the ease of programming of the interpretive pseudocode systems.
Fortran I
– Fortran I was described in October 1956. It included input/output formatting, variable names of up to six characters, and user-defined subroutines. The early success of Fortran I was shown in results of a survey made in April 1958. Most of the code written for 704s was being written in Fortran, despite skepticism of most programming world a year earlier
Fortran II
– Fortran II compiler was distributed on 1958. It fixed many bugs in the Fortran I and added some significant features to the language, the most important being the independent compilation of subroutines. Few years after, it also added support for double precision and complex data types
Fortran IV
– Fortran IV was developed in 1961 and released in 1962. It became the most used programming language of its time. IT contains many improvements from Fortran II, like explicit type declarations for variables, logical if construct and capability of passing subprograms as parameters to other subprograms

5. Which of three original goals of the Fortran design committee, in your opinion, was most difficult to achieve at that time?

To reach the efficiency of hand-coded program maybe was quite hard at that time. We only had computer which has small memories in past, it was hard to create a fast compiler of hand-coded program, especially when the program is typed quite long. it obviously consume more memories.

6. Make an educated guess as to the most common syntax error in C programs.

The most common syntax error in C programs is the punctuator (such as semicolons), brackets and operators placement. It is the most common error as programmers tend to forget to put a semicolon on every end of statements due to lack of meticulousness. Or, they either forget to put an closing bracket or placed the closing bracket on the wrong spot. This might happen due to lack of readability and writability of a code.

7. LISP began as a pure functional language buat gradually acquired more and more imperative features. Why?

Because LISP completely dominated AI applications for a quarter century. Many contemporary implementations are compiled, and the resulting code is much faster than running the source code on a interpreter. In addition to its success in AI, LISP pioneered functional programming, which has proven to a lively area of research in programming languages.

9. Why, in your opinion, did Fortran allow names that began with I,J,K,L,M, and N as implicitly integer type ?
Because people at that time, especially scientists and engineers, used those alphabets to represent an unknown number as variable so they can process the problem. In my pure opinion, it is because it’s easier to use those alphabets as names since most likely Fortran was not yet used to develop a program that is too complex / has too many parts that using such variable name would confuse the programmer

10. Outline the major developments in ALGOL 60.

The concept of block structure was introduced, two different means of passing parameters to subprograms were allowed, procedures were allowed to be recursive, stack-dynamic arrays were allowed.

13. What is the primary reason why C became more widely used than Fortran?

Fortran can’t allocate new variables or space during execution time. This made recursive subprograms to run and made it difficult to implement a data structure that change shape dinamically. Kinds of program being built were simpler than recent. Thus Fortran are not able to accomodate the requirements of recent software developments. But, C is able to cover most of Fortran’s weakness on developing software that has advanced requirements. That is why C is more widely used.

16. What is your opinion of the argument that languages that are too complex are too dangerous to use, and we should therefore keep all languages small and simple ?
I strongly disagree with that argument. Languages that are too complex, in my opinion is not dangerous at all – in case that the programmer who use the language knows exactly what he / she is doing. High complexity means that the program will be able to do more than simple coded programs, as complexity is defined as orthogonality. There is no use in keeping all languages small and simple. Since if there’s a language that some thinks too complex, people just don’t have to use it as standard. Instead, they can use simple ones as the standard.

Concepts of Programming Language Chapter 1 (Preliminaries)

Review Questions

1. why is it useful for a programmer to have some background in language design, even though he or she may never actually design a programming language?

because understanding the basic makes it easier ti learn and adopt new languages. it also helps to design and develop more better software. programmer’s need to understand how their code will work to ensure it is fault tolerant and high performing.

2. How can knowledge of programming language characteristics benefit the whole computing community?

it will provide insight on what functionally that certain languages provide works well, and what doesn’t work well. this also will allow programmers design languages that contain the great characteristics of languages.

3. What programming language has dominated scientific computing over the past 50 years?

programming language that has dominated scientific computing over the past 50 years is Fortran. It is still used because the primary concern of scientific applications is efficiency.

4. What programming language has dominated business applications over the past 50 years?

programming language that has dominated business applications over the past 50 years is COBOL. COBOL is an acronym for Common Business-Oriented Language. this programming language is one of the oldest programming languages, primarily designed by Grace Hopper. Defining its primary domain in business, finance, and administrative systems for companies and governments.

5. What programming language has dominated artificial intelligence over the past 50 years?

Lisp (List Processing) is one of programming language with a long history and a distinctive, fully parenthesized polish prefix notation. this is the second oldest high level programming language in widespread and also has changed a great deal since its early days. it was originally created as a practical mathematical notation for computer programs, influenced by the notation of Alonzo Church’s lambda calculus. it quickly became the favored programming language for AI (artificial intelligence) research. Lisp pioneered tree data structures, automatic storage management, dynamic typing, and the self-hosting compiler.

6. In What language is most of UNIX written?

C

7. What is the disadvantage of having too many features in a language?

It tends to lead to knowing only a subset.

8. How can user-defined operator overloading harm the readability of a program?

If the operations are used in odd unintuitive ways.

9. What is one example of a lack of orthogonality as a primary design criterion?

C has 2 structured data types (arrays and structs) arrays can be returned from functions butstructs can’t.

10. What language used orthogonality as a primary design criterion?

Language that used orthogonality as a primary design criterion is ALGOL 68. The main aims and principles of design of ALGOL 68 :

1. Completeness and clarity of design

2. Orthogonal design

3. Security

4. Efficiency : Static mode checking, mode-independent parsing, Independent compilation, Loop optimization, representations – in minimal & larger character sets.

11. What primitive control statement is used to build more complicated control statements in languages that lack them?

The selection statement plus GOTO is used to build more complicated control statements such as FOR loop.
12. What construct of a programming language provides process abstraction?

Subprograms.
13. What does it mean for a program to be reliable?

A program is said to be reliable if it performs to its specifications under all conditions.
14. Why is type checking the parameters of a subprogram important?

because it can lead to lots of hard to debug errors.
15. What is aliasing?

Aliasing is two or more distinct names that can be used to access the same memory cell.

16. What is Exception Handling?

is the process of responding to the occurrence during computation, often changing the normal flow of program execution and provided by specialized programming language constructs or computer hardware mechanisms. it is able to intercept run-time errors or take corrective measures. Commonly, it is resolved by saving the current state of execution.

17. Why is readability important to writability?

Readability is important to writability because if programming language is difficult to read and understand then it can be difficult for a programmer to create new code that might need to interact or use other code.
18. How is the cost of compilers for a given language related to the design of that language?

Many run time checks will prohibit fast code execution. If optimization is used compiling will be slower but execution will be faster.
19. What have been the strongest influences on programming language design over the past 50 years?

The basic architecture of computers(von Neumann).
20. What is the name of the category of programming languages whose structure is dictated by the von Neumann computer architecture?

Imperative languages
21. What two programming language deficiencies were discovered as a result of the research in software development in the 1970s?

Incompleteness of type checking and inadequacy of control statements
22. What are the three fundamental features of an object-oriented programming language?

Data abstraction,inheritance and dynamic (run-time) method.
23. What language was the first to support the three fundamental features of object-oriented programming?

Smalltalk.
24. What is an example of two language design criteria that are in direct conflict with each other?

Reliability and cost of execution
25. What are the three general methods of implementing a programming language?

Compilation,pure interpretation, hybrid implementation systems
26. Which produces faster program execution, a compiler or a pure interpreter?

Compiler.
27. What role does the symbol table play in a compiler?

the symbol table serves as a database for the compilation process in a compiler.
28. What is the utility of byte code?

29. What is a hybrid implementation system?

hybrid implementation system is a method that is not as fast as compiled languages, they are faster than interpreted languages and compile faster than compiled languages. The source language statements are decoded only once.
30. What are the advantages of using Borland JBuilder?

the advantages are :

1. provides the usual drag and drop, wysiwyg ui designer

2. comes with a set of neat data-aware swing components for rapid database application development.

3. supports pluggable add in’s.


Problem Set

2. Who is said to be the first programmer in human history?

Augusta Ada Byron or more known as Ada Lovelace, was an English mathematician and worked on Charles Babbage’s early mechanical general-purpose computer, the Analytical Engine. Her notes on the engine include what is recognised as the first algorithm intended to be processed by machine so that she is often considered the world’s first computer programmer.

As a young adult, her mathematical talents led her to an ongoing working relationship and friendship with fellow British mathematician Charles Babbage, and in particular Babbage’s work on the analytical engine. Between 1842 and 1843, she translated an article by Italian military engineer Luigi Menabrea on the engine, which she supplemented with an elaborate set of notes of her own, simply called Notes. These notes contain what is considered the first computer program – that is, an algorithm encoded for processing by a machine. Lovelace’s notes are important in the early history of computers. She also developed a vision on the capability of computers to go beyond mere calculating or number-crunching while others, including Babbage himself, focused only on those capabilities

3. What are the disadvantages of multiple programming language?

multiple programming language gives the disadvantages such as there are so many syntax that programmer needs to know.

4. In what way do the languages for scientific applications differ from the languages for business applications?

language for scientific application is mainly used for calculation and computing formula. it relatively uses simple data structures such as arrays and matrices.But language for business application commonly used to produce report and store decimal and character. it is able to specify decimal arithmetic operations.

5. In what way do the languages for artificial intelligence differ from the languages for web software?

Language for artificial intelligence uses of symbolic computations. it means that symbols are manipulated and more coneniently done with linked lists of data rather than arrays. the developer defines knowledge to be used only.

Language for web software uses markup languages where this is a modern system for annotating a document in a way that is syntactically distinguishable from the text. this is also use scripting and general purpose. the developer is obliged to define all the ways the web could follow.

9. Explain how orthogonality in a programming language is closely related to simplicity.

orthogonality in a programming language is relatively a small set of primitive constructs that can be combined in a relatively small number of ways to build the control and data structures of the language. Orthogonality follows from a symmetry of relationships among primitives. With orthogonality, it could compress the size of large amount of primitive feature to fewer number of primitive feature.

14. Describe the advantages and disadvantages of using different computer architecture for writing a program.

the disadvantage of using different computer architecture is it could create an incompability between the program and computer architecture itself, it also brings to an error. The advantage of using different computer architecture is it will allow the programmer to build their own program compatible with different computer architectures they have had.

15. Name some languages which use preprocessor directives and some which don’t. What are the advantages and disadvantages of preprocessor directives?

C,C++, and C# use preprocessor directives, it brings some advantages such as :

1. reduces length of the code and time spent for writing the codes.

2. increases execution speed of the program.

3. increases readability and writability of the program.

but somehow there are still some disadvantages such as :

1. Increases size memory of the program.

2. macros can only return the last value processed.

3. Causes an error.

17. Some programming languages – for example, SQL – use “=” to check the equality of two expressions, while C uses it to assign values to variable. Which of these, in your opinion, is most natural and least likely to result in syntax errors?

The using of “=” to check the equality of two expressions in SQL is more natural than in C, because in C, we use “==” to check do the first expression equals to the second expression or not. We have learned this symbol to check the equality from the basic mathematics before so it will reduce the possibility of syntax errors in this things. However, it becomes difficult to assign values to variable because the symbol of “=” has been used so that the use of C symbols are easier than SQL. C language has specified “=” symbol to assign values to variable and “==” to comparing two expressions.