Concept of Programming Language Chapter: 16

Lecturer : Mr. Tri Djoko Wahjono, Ir. M.Sc

BY : NETTY SETIAWAN

from: 02PCT

NIM: 1601221572

REVIEW QUESTIONS

1.   What are 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?

Two parts of a compound term are:  a functor, which is the function symbol that names the relation, and an ordered list of parameters, which together represent an element of the relation.

3.   What are the two modes in which a proposition can be stated?

Propositions can be stated in two modes: one in which the proposition is defined to be true, and one in which the truth of the proposition is something that is to be determined. In other words, propositions can be stated to be facts or queries.

5.   What are antecedents? Consequents?

Antecedents are the right side of clausal form propositions, whereas Consequents are the left side of clausal form propositions, because it is the consequence of the truth of the antecedent.

7.   What are the forms of Horn clauses?

Horn clauses can be in only two forms: They have either a single atomic proposition on the left side or an empty left side. The left side of a clausal form proposition is sometimes called the head, and Horn clauses with left sides are called headed Horn clauses. Headed Horn clauses are used to state relationships, such as

likes( bob, trout ) likes( bob, fish ) x fish( trout )

11. What is an uninstantiated variable?

An uninstantiated variable is a variable that has not been assigned a value.

13.  What is a conjunction?

Conjunctions contain multiple terms that are separated by logical AND operations.

PROBLEM SET

1.”All predicate calculus propositions can be algorithmically converted to clausal form”. Is this statement true or false?

This statement is true. Nilsson (1971) gives proof that this can be done, as well as a simple conversion algorithm for doing it.

2. Describe how a logic programming language is different from a general programming language.

Programming that uses a form of symbolic logic as a programming language, unlike other general programming language, is often called logic programming; languages based on symbolic logic are called logic programming languages, or declarative languages.

10.  Using the internet for reference, find some of the applications of expert systems.

• Expert system in healthcare: The Electronic health record (EHR) is designed to replace the traditional medical and bring together a more versatile, expansive and robust expert system to provide greater quality care.

• Expert systems in the financial field: Loan departments are interested in expert systems for morgages because of the growing cost of labour, which makes the handling and acceptance of relatively small loans less profitable.

• A new application for expert systems is automated computer program generation. Funded by a US Air Force grant, an expert system-based application (hprcARCHITECT) that generates computer programs for mixed processor technology (FPGA/GPU/Multicore) systems without a need for technical specialists has recently been commercially introduced.

Concept of Programming Language Chapter: 15

Lecturer : Mr. Tri Djoko Wahjono, Ir. M.Sc

BY : NETTY SETIAWAN

from: 02PCT

NIM: 1601221572

REVIEW QUESTIONS

2.   What does a lambda expression specify?

A lambda expression specifies the parameters and the mapping of a function.

3.   What data types were parts of the original LISP?

Atoms and lists.

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.

8.   What are the three parameters to IF?

Three parameters to IF are: a predicate expression, a then expression, and an else expression.

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).

22.  What happens during reader phase of a common LISP language processor?

During reader phase of a common LISP language processor,  There is a special kind of macro, named reader macros or read macros, that are expanded.  A reader macro expands a specific character into a string of LISP code. For example, the apostrophe in LISP is a read macro that expands to a call to QUOTE.

24.  What is stored in an ML evaluation environment?

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.

29. What is a curried function?
Curried function let 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.

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.

35.   When is a programming language called a nonstrict language?

A language is nonstrict if it does not have the strict requirement.

 43.  What is the syntax of a lambda expression in F#?

The following lambda expression illustrates their syntax:
(fun a b −> a / b)

PROBLEM SET

2.  Give the general form of function declaration in ML.

Function declarations in ML appear in the general form
fun function_name( formal parameters ) = expression;

8.   How is the functional operator pipeline ( | > )used in F#?

The pipeline operator is a binary operator that sends the value of its left operand, which is an expression, to the last parameter of the function call, which is the right operand. It is used to chain together function calls while flowing the data being processed to each call.

Consider the following example code, which uses the high-order functions filter and map:

let myNums = [1; 2; 3; 4; 5]
let evensTimesFive = myNums

|> List.filter (fun n −> n % 2 = 0)

10.  What does  the following Scheme function do?

(define ( x lis)
(cond
(( null? lis) 0 )
(( not(list? (car lis)))
(cond
((eq? (car lis) #f) (x (cdr lis)))
(else (+1 (x (cdr lis))))))
(else (+ (x (car lis))  (x (cdr lis))))

x returns the number of non-#f atoms in the given list

|> List.map (fun n −> 5 * n)

Concept of Programming Language Chapter: 14

Lecturer : Mr. Tri Djoko Wahjono, Ir. M.Sc

BY : NETTY SETIAWAN

from: 02PCT

NIM: 1601221572

REVIEW QUESTIONS

2.   When is an exception thrown or raised?

An exception is raised when its associated event occurs.

3.   What are the advantages of having support for exception handling builtin to language?

• First, without exception handling, the code required to detect error conditions can considerably clutter a program.

• Another advantage of language support for exception handling results from exception propagation. Exception propagation allows an exception raised in one program unit to be handled in some other unit in its dynamic or static ancestry.

• A language that supports exception handling encourages its users to consider all of the events that could occur during program execution and how they can be handled. This approach is far better than not considering such possibilities and simply hoping nothing will go wrong.

9.   What is the scope of exception handlers in Ada?

An exception handler in Ada can occur in either a  subprogram body, a package body, a task, or a block

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

There are four exceptions that are defined in the default package, Standard:

Constraint_aError
Program_Error
Storage_Error
Tasking_Error

12.   What is the use of Suppress pragma in Ada?
The suppress pragma is used to disable certain run-time checks that are parts of the built-in exceptions in Ada.

14. What is the name of all C++ exception handlers?
The name of all C++ exception handlers is Try clause.

15.  Which standard libraries define and throw the exception out_of_range in C++?

The exception out_of_range is thrown by library container classes.

16.  Which standard libraries define and throw the exception overflow_error in C++?

The exception overflow_error is thrown by math library functions.

32.  What is event-driven programming?
Event-driven programming is a programming where parts of the program are executed at completely unpredictable times, often triggered by user interactions with the executing program.

33.   What is the purpose of a Java JFrame?
The JFrame class defines the data and methods that are needed for frames. So, a class that uses a frame can be a subclass of JFrame. A JFrame has several layers, called panes.

PROBLEM SET

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

Early programming languages were designed and implemented in such a way that the user program could neither detect nor attempt to deal with such errors. In these languages, the occurrence of such an error simply causes the program to be terminated and control to be transferred to the operating system.

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

In C subscript ranges are not checked. Java compilers usually generate code to check the correctness of every subscript expression. If any exception generates, then an unchecked exception is thrown.

4.   What are the different approaches to handle checked exception in Java?

In Java there are basically two types of exceptions: Checked exceptions and unchecked exceptions.

Checked exceptions must be explicitly caught or propagated as described in Basic try-catch-finally Exception Handling. Unchecked exceptions do not have this requirement. They don’t have to be caught or declared thrown.
Checked exceptions in Java extend the java.lang.Exception class. Unchecked exceptions extend the java.lang.RuntimeException.

14.  Summarize the arguments in favor of the termination and resumption models of continuation.

The resumption model is useful when the exception is only an unusual condition, rather than an error. The termination model is useful when the exception is an error and it is highly unlikely that the error can be corrected so that execution could continue in some useful way.

 

Concept of Programming Language Chapter: 13

Lecturer : Mr. Tri Djoko Wahjono, Ir. M.Sc

BY : NETTY SETIAWAN

from: 02PCT

NIM: 1601221572

REVIEW QUESTIONS

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)

5.   What level of program concurrency is best supported by MIMD computers?

Unit-level concurrency is best supported by MIMD computers.

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?

A scheduler manages the sharing of processors among the tasks. If there were never any interruptions and tasks all had the same priority, the scheduler could simply give each task a time slice, such as 0.1 second, and when a task’s turn came, the scheduler could let it execute on a processor for that amount of time.

16.   What is a task descriptor?
A 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?

A binary semaphore is  a semaphore that requires only a binary-valued counter. A counting semaphore is a synchronization object that can have an arbitrarily large number of states.

30.  What is the purpose of an Ada terminate clause?

A terminate clause, when selected, means that the task is finished with its job but is not yet terminated. Task termination is discussed later in this section.

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?

The join method is used to force a method to delay its execution until the run method of another thread has completed its execution.

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 take the function as its parameter and 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.

60.  What is the type of an F# heap-allocated mutatable variable?

A mutable heap-allocated variable is of type ref

63.  What is the purpose of the FORALL statement of High-Performance Fortran and Fortran?

The FORALL statement specifies a sequence of assignment statements that may be executed concurrently.

PROBLEM SET

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

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).

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 Language Chapter: 12

REVIEW QUESTIONS

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

The problems associated with programming using abstract data types are:

• 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.

3.   What is the advantage of inheritance?

The advantage of inheritance is inheritance offers a solution to both the modification problem posed by abstract data type reuse and the program organization problem. If a new abstract data type can inherit the data and functionality of some existing type, and is also allowed to modify some of those entities and add new entities, reuse is greatly facilitated without requiring changes to the reused abstract data type.

4.   What is message protocol?

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

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.

8.   What is an abstract method? What is an abstract class?

An abstract method is an implemented method which all of descendant class should have and it is included in Building.

An abstract class is  a class that includes at least one abstract method.

10.  What is an inner class?

An inner class is  a nonstatic class that is nested directly in another class.

12.  From where are Smalltalk objects allocates?

All 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. Objective-C only supports single inheritance.

31.  What is the root class in Objective-C?

The root class in Objective-C is called NSObject

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.

49.  What access controls does Ruby support for instance variables?

Access control in Ruby is different for data than it is for methods. All instance data has private access by default, and that cannot be changed. If external access to an instance variable is required, accessor methods must be defined.

PROBLEM SET

2.    In what ways can “compatible “ be defined for the relationship between an overridden method and the overriding method?

Every overriding method must have the same number of parameters as the overridden method and the types of the parameters and the return type must be compatible with those of the parent class.

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.

•  The meaning of protected member access specifier is somewhat different in Java. In Java, protected members of a class “A” are accessible in other class “B” of same package, even if B doesn’t inherit from A (they both have to be in the same package).

•  Java uses extends keyword for inheritence. Unlike C++, Java doesn’t provide an inheritance specifier like public, protected or private. Therefore, we cannot change the protection level of members of base class in Java, if some data member is public or protected in base class then it remains public or protected in derived class. Like C++, private members of base class are not accessible in derived class. Unlike C++, in Java, we don’t have to remember those rules of inheritance which are combination of base class access specifier and inheritance specifier.

5.    Compare abstract class and interface in Java.

• First and major difference between abstract class and interface is that, abstract class is a class while interface is a interface, means by extending abstract class you can not extend another class because Java does not support multiple inheritance but you can implement multiple inheritance in Java.
• Second difference between interface and abstract class in Java is that you can not create non abstract method in interface, every method in interface is by default abstract, but you can create non abstract method in abstract class. Even a class which doesn’t contain any abstract method can be abstract by using abstract keyword.
• Third difference between abstract class and interface in Java is that abstract class are slightly faster than interface because interface involves a search before calling any overridden method in Java. This is not a significant difference in most of cases but if you are writing a time critical application than you may not want to leave any stone unturned.
• Fourth difference between abstract class vs interface in Java is that, interface are better suited for Type declaration and abstract class is more suited for code reuse and evolution perspective.
• Another notable difference between interface and abstract class is that when you add a new method in existing interface it breaks all its implementation and you need to provide an implementation in all clients which is not good. By using abstract class you can provide default implementation in super class.

7.   What is one programming situation where multiple inheritance has a significant disadvantage over interfaces?

A situation when there are two classes derived from a common parent and those two derived class has one child.

9.   Give an example of inheritance in C++, where a subclass overrides the superclass methods.

class Enemy{

protected:

int Hp;

public:

void attack(){

cout<<“Enemy Attacks using GUN!!”<<endl;
}
};

class BossEnemy: public Enemy{

public:

void attack(){

cout<<“Boss Enemy attacks using MAGIC!!”<<endl;
}
};

10.  Explain one advantage of inheritance.

One of the key benefits of inheritance is to minimize the amount of duplicate code in an application by sharing common  code amongst several subclasses. Where equivalent code exists in two related classes, the hierarchy can usually be  refactored to move the common code up to a mutual superclass. This also tends to result in a better organization of  code and smaller, simpler compilation units.

17.  What are the different options for object destruction in Java?

There is no explicit deallocation operator. A finalize method is implicitly called when the garbage collector is about to reclaim the storage occupied by the object.

Concept of Programming Language Chapter: 11

REVIEW QUESTIONS

1.   What are two kinds of abstractions in programming language?

Two kinds of abstractions in programming languages are process abstraction and data abstraction.

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

The first design issue for abstract data types is the form of the container for the interface to the type. The second design issue is whether abstract data types can be parameterized. The third design issue is what access controls are provided and how such controls are specified.

6. Explain how information hiding is provided in an Ada package.
There are two approaches to hiding the representation from clients in the package specification. One is to include two sections in the package specification—one in which entities are visible to clients and one that hides its contents.

9. What is in an Ada package specification? What about a body package?
Package specification, is an Ada package which provides the interface of the encapsulation (and perhaps more)
Body package, is an Ada package which provides the implementation of most, if not all, of the entities named in the associated package specification.

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

The with clause makes the names defined in external packages visible.

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

The purpose of a C++ destructor is to deallocate heap space (memory) that the object or class used.

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

A destructor has no return types.

20.  What is the use of limited private types?

Limited private types are useful when the usual predefined operations of assignment and comparison are not meaningful or useful.

21 What are initializers in Objective-C?

Intializers in Objective-C are constructors.

26.   Why does Java not have destructors?

The purpose of a Destructor is usually to clear off unused variables and clean up the memory. Java has in built memory handling mechanisms (Garbage collection) that clear off unused memory automatically. Hence there is no requirement for destructor methods.

27.  Where are Java methods defined?

Methods in Java must be defined completely in a class.

28. Where are Java classes allocated?

Java classes are allocated  from the heap and accessed through reference variables.

PROBLEM SET

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

• There is no memory leak such as dangling pointers or unnamed variables.

• Memory access via pointer arithmetic – this is fundamentally unsafe. Java has a robust security model and disallows pointer arithmetic for this reason.

• Array access via pointer offsets – Java does this via indexed array access so you don’t need pointers. A big advantage of Java’s indexed array access is that it detects and disallows out of bounds array access, which can be a major source of bugs.

• References to objects – Java has this, it just doesn’t call them pointers. Any normal object reference works as one of these.

8.   What are the drawbacks of user-defined generic classes in Java 5.0?

Some drawbacks of user-defined generic classes in Java 5.0 are: for one thing, they cannot store primitives. Second, the elements cannot be indexed. Elements must be added to user-defined generic collections with the add method.

9.   What happens if the constuctor is absent in Java and C++?

It will be automatically made by the compiler.

11.  Why is the destructor of C# rarely used?

Destructors in C# are rarely used because it uses garbage collection for most of its heap objects.

12.  How are classes in Ruby made dynamic?

Classes in Ruby are dynamic in the sense that members can be added at any time. This is done by simply including additional class definitions that specify the new members.

Concept of Programming Language Chapter: 10

REVIEW QUESTIONS

1. What is the definition used in this chapter for “simple” subprograms?
By “simple” it means that subprograms cannot be nested and all local variables are static

4. What is the task of a linker?
Its first task is to find the files that contain the translated subprograms referenced in that program and load them into memory. Then, the linker must set the target addresses of all calls to those subprograms in the main program to the entry addresses of those subprograms.

6. What is the difference between an activation record and an activation record instance?
An activation record is the format, or layout, of the moncode part of a subprogram, whereas an activation record instance is a concrete example of an activation record, a collection of data in the form of an activation record.

8. What kind of machines often use registers to pass parameters?
RISC machines, parameters are passed in registers

11. What is an EP, and what is its purpose?
EP is a point or first address of the activation record instance of the main program. It is required to control the execution of a subprogram.

14. What are two potentialproblems with the static-chain method?
•  It is difficult for a programmer working on a time-critical program to estimate the costs of nonlocal references, because the cost of each reference depends on the depth of nesting between the reference and the scope of declaration.
•  Subsequent code modifications may change nesting depths, thereby changing the timing of some references, both in the changed code and possibly in code far from the changes.

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.

8.   Pascal allows gotos with nonlocal targets. How could such statements be handled if static chains were used for nonlocal variable access? Hint:Consider the way the correct activation record instance of the static parent of a newly enacted procedure is found(see Section 10.4.2).

Based on the hint statement, the target of every goto in a program could be represented as an address and a nesting_depth, where the nesting_depth is the difference between the nesting level of the procedure that contains the goto and that of the procedure containing the target. Then, when a goto is executed, the static chain is followed by the number of links indicated in the nesting_depth of the goto target. The stack top pointer is reset to the top of the activation record at the end of the chain.

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.

Concept of Programming Language Chapter: 9

REVIEW QUESTIONS

1.   What are the three general characteristics of subprograms?

• Each subprogram has a single entry point.
• The calling program unit 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.

2.   What does it mean for a subprogram to be active?

A subprogram is said to be active if, after having been called, it has begun execution but has not yet completed that execution.

3.   What is given in the header of a subprogram?

• First, it specifies that the following syntactic unit is a subprogram definition of some particular kind.1 In languages that have more than one kind of subprogram, the kind of the subprogram is usually specified with a special word.
• Second, if the subprogram is not anonymous, the header provides a name for the subprogram.
• Third, it may optionally specify a list of parameters.

 8.   What are formal parameters? What are actual parameters?

Formal parameters are The parameters in the subprogram header. They are sometimes thought of as dummy variables because they are not variables in the usual sense.
Actual parameters are a list of parameters to be bound to the formal parameters of the subprogram.

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

The advantage of keyword parameters 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.

15.   What are the three semantic models of parameter passing?

• They can receive data from the corresponding actual parameter;

• they can transmit data to the actual parameter; or

• they can do both.

These models are called in mode, out mode, and inout mode, respectively.

24.   What is an overloaded subprogram?

An overloaded subprogram is a subprogram that has the same name as another subprogram in the same referencing environment.

25.   What is ad hoc binding?

Ad hoc binding is the environment of the call statement that passed the subprogram as an actual parameter30. What are the design issues for functions?

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

 

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.

Arguments for:

It allows the developer to program using notation “closer to the target domain” and allows user-defined types a similar level of syntactic support as types built into the language. It can easily be emulated using function calls.

Arguments against:

It can be implemented according to user’s want, eventhough it is not logically true.

I think such  user-defined operator overloading is good as long as user use it according to its logical rules. User must use for example, + operator to be overloaded to implement “add” not “substraction”. And sometimes, in C++ there is condition when user need to add many data in class, so user-defined operator like this is needed to make it easier.

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:
void swap(int a, int b) {
int temp;
temp = a;
a = b;
b = temp;
}

void main() {
int value =1, list[5]= {2,4,6,8,10};
swap (value,list[0]);
swap(list[0],list[1]);
swap(value,list[value]);
}
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
b. Passed by reference
c. Passed by value-result

Answer:

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:
void fun(int first, int second){
first+=first;
second+=second;
}

void main(){
int list[2] = { 3 , 5 };
fun(list[0], list[1]);
}
 for each of the following parameter-passing methods, what are the values of the list array after execution?
a. Passed by value
b. Passed by reference
c. Passed by value-result

Answer:

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 }

Concept of Programming Language Chapter: 8

REVIEW QUESTIONS

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 Böhm and Jocopini prove about flowcharts?

Böhm and Jacopini proved that all algorithms that can be expressed by flowcharts can be coded in a programming language with only two control statements: one for choosing between two control flow paths and one for logically controlled
iterations

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? All selection and iteration constructs control the execution of code segments, and the question is whether the execution of those code segments always begins with the first statement in the segment.

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

An F# selector have an else clause when 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?
• Is execution flow through the structure restricted to include just a single selectable segment?
• How are the case values specified?
• How should unrepresented selector expression values be handled, if at all?

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?

16.  What is a pretest loop statement? What is a posttest loop statement?

Pretest loop statements are set of statements to be executed repeatedly in which the test for loop completion occurs before the loop body is executed

Posttest loop statements are set of statements to be executed repeatedly in which the test for loop completion occurs after the loop body is executed

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

• Should the control be pretest or posttest?
• Should the logically controlled loop be a special form of a counting loop or a separate statement?

26.  What is a user-defined iteration control?

A user-defined iteration control is the one that issues a special call to the iterator, in which the iterator is called at the beginning of each iteration, and each time it is called, the iterator returns an element from a particular data structure in some specific order.

 

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.

if x > y :
x = y
print “case 1”
All statements equally indented are included in the compound statement.

5.    What are the arguments pro and con, for Java’s approach to specify compound statements in control statements?

• Compound statements are required in control statements when the body of the if or else clause requires multiple statements.

• Java uses braces to form compound statements, which serve as the bodies of if and else clauses.

14.  State one of the main legitimate needs for gotos.

One of the main legitimate needs for gotos—premature exits from loops—can be met with highly restricted branch statements, such as break.

Concept of Programming Language Chapter: 7

REVIEW QUESTIONS

2.   What is a ternary operator?

A ternary operator is a operator which has three operands.

10.  What is a conditional expression?

Conditional expression is a feature of a programming language which perform different computations or actions depending on whether a programmer specified boolean condition evaluates to true or false.

11.  What is an overloaded operator?

Arithmetic operators are often used for more than one purpose. This multiple use of an operator is called overloaded operator.

15.  What is referential transparency?

The concept of referential transparency is related to and affected by functional side effects. A program has the property of referential transparency if any 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.

18.  What is short-circuit evaluation?g

A short-circuit evaluation of an expression is one in which the result is determined without evaluating all of the operands and/or operators. For example, the value of the arithmetic expression (13 * a) * (b / 13 – 1) is independent of the value of (b / 13 – 1) if a is 0, because 0 * x = 0 for any x. So, when a is 0, there is no need to evaluate (b / 13 – 1) or perform the second multiplication.

24.  What two languages include multiple assignments?

Two languages include multiple assignments are Perl and Ruby.

28.  What is a cast?

A cast is an explicit type conversion.

 

PROBLEM SET

5.   Should C’s assigning operations (for example, +=) be included in other languages (that do not already have them) ? Why or why not?

Yes, I think C’s assigning operations  (for example, +=) should be included in other languages, because it is simpler and easier to write a calculation in the complier. For example we just can type sum+=2 which is simpler than sum=sum+2.

7.   Describe a situation in which the add operator in a programming language would not be commutative.

In many programming languages, the operands of an addition are actually memory locations, and the result of an addition is stored in the same location as one of the operands, so the operation is not commutative. A+B may not give quite the same result as B+A, because of the storage location of the result.

8.  Describe a situation in which the add operator in a programming language would not be associative.

Consider the integer expression A + B + C. Suppose the values of A, B, and C are 20,000, 25,000, and -20,000, respectively. Further suppose that the machine has a maximum integer value of 32,767. If the first addition is computed first, it will result in overflow. If the second addition is done first, the whole expression can be correctly computed.

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.

Answer:

a. 7

b. 12

21.  Why does java specify that operands in expressions are all evaluated in left-to-right order?

In Java, the operators are evaluated from left to right as long as it does not violate the precedence and associativity. This is known as the Java expression evaluation in contrast to the arithmetical evaluation.Java expression evaluation is equivalent to the arithmetic evaluation. Java expression evaluation is easier to implement and more efficient to execute.