CONCEPTS OF PROGRAMMING LANGUAGES – CHAPTER 16(LOGIC PROGRAMMING LANGUAGES)

Published June 28, 2013 by patriciaivanapurnomo

Lecture: Mr. Tri Djoko Wahjono (D0206)

REVIEW QUESTIONS
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 ordered list of parameters.

3. What are two modes in which a proposition can be stated?
Propositions can be started 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.

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

7. What are the forms of Horn clauses?
Horn clauses can be in only two forms : single atomic proposition on the left side or right side.

8. What is the basic concept of declarative semantics?
Basic concept of declarative semantics is there is a simple way to determine the meaning of each statement, and it does not depend on how the statement might be used to solve a problem.

11. What is an uninstantiated variable?
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.
Logical programming language uses a form of symbolic logic, the syntax of logic programming logic is remarkably different from that of the imperative and functional languages.

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.

CONCEPTS OF PROGRAMMING LANGUAGES – CHAPTER 15(FUNCTIONAL PROGRAMMING LANGUAGE)

Published June 28, 2013 by patriciaivanapurnomo

Lecture: Mr. Tri Djoko Wahjono (D0206)

REVIEW QUESTIONS
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.

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

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

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.

27. What is the use of the fn reserved word in ML?
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.

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.

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 features of Haskell.
Haskell features lazy evaluation, pattern matching, list comprehension, type classes, and type polymorphism.

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, t the last parameter of the function call, which is the right operand. It is used to chain together function calls while following the data being processed to each call.

9. What does the following Scheme function do?
(define ( y s lis)
(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.

CONCEPTS OF PROGRAMMING LANGUAGES – CHAPTER 14(EXCEPTION HANDLING AND EVENT HANDLING)

Published June 28, 2013 by patriciaivanapurnomo

Lecture: Mr. Tri Djoko Wahjono (D0206)

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 built in to a language?
Less clutter to detect errors, allowing a single number of handling to handle a number of events.

4. Give an example of hardware-detectable exceptions.
Division by zero

6. What is exception handling 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.

11. are they any predefined exceptions in Ada?
Yes.

12. What is the use of Suppress pragma in Ada?
Disabling certain run-time checks that are parts of the built-in exceptions.

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

30. In which version were assertions added to Java?
Assertions were added to Java in version 1.4.

31. What is the use of the assert statement?
The assert statement is used for defensive programming. A program may be written with many assert statements, which ensure that the program’s computation is on track to produce correct results.

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.

34. What are the different forms of assert statement?
– Assert condition.
– Assert condition : expression.

36. Which package in java contains all the event related classes.
java.awt.event package.

PROBLEM SET
1. What mechanism did early programming languages provide to detect or attempt to deal with errors?
Most of computer hardware system are capable of detecting certain run-time error conditions, such as floating-point overflow. 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. The typical operating system reaction to a run-time error is to display a diagnostic message, which may be meaningful and therefore useful, or highly cryptic. After displaying the message, the program is terminated.

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.

5. From a textbook on FORTRAN, determine how exception handling is done in FORTRAN programs.
For example, a Fortran “Read” statement can intercept inputerrors and end-of-file conditions, both of which are detected by the input device hardware. In both cases, the Read statement can specify the label of some statement in the user program that deals with the condition. In the case of the end-of-file, it is clear that the condition is not always considered an error. In most cases, it is nothing more than a signal that one kind of processing is completed and another kind must begin. In spite of the obvious difference between end-of-file and events that are always errors, such as a failed input process, Fortran handles both situations with the same mechanism.

7.In languages without exception-handling facilities, we could send an error-handling procedure as parameter to each procedure that can detect errors than must be handled. What disadvantage 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.

9. Write a comparative analysis of the throw clause and throws clause of Java.
Throw statement is used to retrieve the name of the class with the actual parameter, while the throws clause of Java specifies that exception class or any of its descendant exception classes can be thrown but no handled by the method.

CONCEPTS OF PROGRAMMING LANGUAGES – CHAPTER 13(CONCURRENCY)

Published June 28, 2013 by patriciaivanapurnomo

Lecture: Mr. Tri Djoko Wahjono (D0206)

REVIEW QUESTIONS
4. What level of program concurrency is best supported by SIMD computers?
Statement-level concurrency.

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

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?
Heavy weight 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.

17. In the context of language support for concurrency, what is a guard?
Guard is a linguistic device that allows the guarded code to be executed only when a specified condition is true.

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.

23. What advantage do monitors have over semaphores?
This solution can provide competition synchronization without semaphores by transferring responsibility for synchronization to the run-time system.

24. In what three common languages can monitors be implemented?
Ada, java, and C#.

34. What does the Java sleep method do?
The Java sleep method blocks the the thread.

35. What does the Java yield method do?
To make the thread is put immediately in the task-ready queue. Making it ready to run.

37. What does the Java interrupt method do?
Interrupt becomes one way to communicate to a thread that it should stop.

42. What kind of Java object is a monitor?
In Java, a monitor can be implemented in a class designed as an abstract data type, with the shared data being the type. Accesses to objects of the class are controlled by adding the synchronized modifier to the access methods.

44. What are the two methods used with Java Semaphore objects?
Acquired and release

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.

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

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 is the best action a system can take when deadlock is detected?
– Interrupt (i.e. send a signal/exception to) all the threads holding the lock. They will have to be able to handle the resulting interrupt, though.
– Kill all the threads/processes involved. This is a drastic action, and it saves the rest of the system at the expense of the risk that some data will probably be lost by the program.

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?
The main problem would be the CPU resources that area allocated to the waiting for the task, if it were to be suspended, the CPU can then be used for other purposes.

CONCEPTS OF PROGRAMMING LANGUAGES – CHAPTER 12(SUPPORT FOR OBJECT-ORIENTED PROGRAMMING)

Published June 28, 2013 by patriciaivanapurnomo

Lecture: Mr. Tri Djoko Wahjono (D0206)

REVIEW QUESTIONS
1. Name two functional languages that support object-oriented programming.
C++ and Java

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.

3. What is the advantage of inheritance?
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.

5. What is an overriding method?
It is a language feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its superclasses or parent classes.

7. What is a dynamic dispatch?
A dynamic dispatch is a kind of polymorphism provided bu the dynamic bindong 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.

11. What is the message protocol of an object?
The message protocol of an objects are all the methods.

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

31. What is the root class in Objective-C?
The predefined root class named NS Object.

33. What is the purpose of an Objective-C category?
To permit the programmer to add methods to an existing class without the need to recompile that class or even have access to its source code.

34. What is the purpose of an Objective-C protocol?
To achievable either as an abstract multiply inherited base class in C++, or as an “interface”.

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 finalizemethod when the garbage collector is about to reclaim the storage occupied by the object.

PROBLEM SET
1 . What important part of support for inheritance is missing in Java?
Java does not support the private and protected derivations of C++. One can surmise that the Java designers believed that subclasses should be subtypes, which they are not when private and protected derivations are supported. Thus, they did not include them.

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.

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 super class. This also tends to result in a better organization of code and smaller, simpler compilation units.

12. Compare inheritance and nested classes in C++. Which of these supports an is-a relationship?
Inheritance is where one class (child class) inherits the members of another class (parent class). Nested class is a class declared entirely within the body of another class or interface. Inheritance does.

13. Describe the mechanism of dynamic dispatch with an example in Java. Is it possible to dynamically dispatch the data members?
In C++, a method must be defined as virtual to allow dynamic binding. In Java, all method calls are dynamically bound unless the called method has been defined as final, in which case it cannot be overridden and all bindings are static. Static binding is also used if the method is static or private, both of which disallow overriding.

16. State why Java is said to be more pure object-oriented than C++.
Java is an object oriented language, which means that one of its core principles is inheritance. All classes (and hence the objects created from them) are derived from a parent. In this way, classes inherit variables, methods, and classes from their parent so that they do not have to redefine them. In Java’s case, the common parent of all classes is Object. This gives every class some basic functionality, such as the equals, toString, and wait methods. Besides uniformity, another advantage of inheritance is clear organization. Imagine if we could not guarantee the comparison of two objects with the equals method. Finally, a global parent class means that every class, no matter how specific, can be generalized into the parent’s type (Object o = new String()).

17. What are the different options for object destruction in Java?
Java have garbage collector, although it still have some issues, the other alternatives would be to use the finalize method.

20. Compare the way Smalltalk provides dynamic binding with that of C++.
While Smalltalk’s dynamic type binding provides somewhat more programming flexibility than the hybrid C++ language, it is far less efficient in the execution.

25. Study and explain private and public modifiers in C++. How do those modifiers differ in C#?
C++ includes both classes and structs, which are nearly identical constructs. The only difference is that the default access modifier for class is private, whereas for structs it is public. C# also has structs, but they are very different from those of C++. In C#, structs are, in a sense, lightweight classes. They can have constructors, properties, methods, and data fields and can implement interfaces but do not support inheritance.

CONCEPTS OF PROGRAMMING LANGUAGES – CHAPTER 11(ABSTRACT DATA TYPES AND ENCAPSULATION CONSTRUCTS)

Published June 28, 2013 by patriciaivanapurnomo

Lecture: Mr. Tri Djoko Wahjono (D0206)

REVIEW QUESTIONS
1. What are the two kinds of abstraction in programming languages?
The two fundamental kinds of abstraction in contemporary programming languages are process abstraction and data abstraction.

2. Define abstract data types.
– the representation of objects of the type is hidden from the program units that use the type.
– the declarations of the type and the protocols of the operations on objects of the type.

3. What are the advantages of the two parts of the definition of abstract data type?
Information hiding, improved readability, and easier to manage.

5. What are the 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.

8. What is the difference between private and limited private types in Ada?
Private types in Ada, it has built-in operations for assignment and comparisons for equality and inequality. Limited private types in Ada, are described in the private section of a package specification, as are non pointer private types. Limited private types are declared to be limited private in the visible part of the package specification.

10. What is the use of the Ada with clause?
With clause makes the names defined in external packages visible.

11. What is the use of the Ada use clause?
Use clause eliminates 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?
C++ is have a few encapsulations. Ada packages are more generalize encapsulations that can define any number of types.

15. What is the purpose of a C++ destructor?
Destructors are often used as a debugging aid, in which case they simply display or print the values of some or all of the object’s data members before those members are deallocated. The name of a destructor is the class’s name, preceded by a tilde (~).

16. What are the legal return types of a destructor?
Neither constructors nor destructors have return types, and neither use return statements. Both constructors and destructors can be explicitly called.

21. What are initializers in Objective-C?
The initializers in Objective-C are constructors.

27. Where are all Java methods defined?
All Java methods are defined in a class.

30. What is a friend function? What is a friend class?
Friend function to allowed access to public, private, or protected data in that class.
Friend class can access the “private” and “protected” members of the class in which it is declared as a friend.

31. What is one reason Java does not have friend functions or friend classes?
Because java has less need for explicit friend declarations.

43. What is a C++ namespace, what is its purpose?
In general, a namespace is a container for a set of identifiers and allows the disambiguation of homonym identifiers residing in different namespaces. The purpose is to help programs manage the problem of global namespace.

PROBLEM SET
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 constructor is absent in Java and C++?
It will be made automatically by the built-up in.

11. Why is the destructor of C# is rarely used?
Because C# 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.

15. Give one capability that Java 5.0 provides which C# 2005 does not.
One capability that Java 5.0 provides that C# 2005 does not is wildcard classes

19. Compare Java’s packages with Ruby’s modules.
In java encapsulation construct called package .Packages can contain more than one type definition, and the types in a package are partial friends of one another.
In ruby a encapsulation construct called module. Modules typically define collections of methods and constants. So, modules are convenient for encapsulating libraries of related methods and constants, whose names are in a separate namespace so there are no name conflicts with other names in a program that uses the module. Modules are unlike classes in that they cannot be instantiated or subclassed and do not define variables.

CONCEPTS OF PROGRAMMING LANGUAGES – CHAPTER 10(IMPLEMENTING SUBPROGRAMS)

Published June 28, 2013 by patriciaivanapurnomo

Lecture: Mr. Tri Djoko Wahjono (D0206)

REVIEW QUESTIONS
1. What is the definition used in this chapter for “simple subprograms”?
Subprogram cannot be nested and all local variables are static.

4.What is the task of a linker?
The task of a linker is to find the files that contain the translated subprograms referenced in that and load them into memory.

8. What kind of machines often use registers to pass parameters?
RISC.

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.

17. Describe the shallow-access method of implementing dynamic scoping.
Shallow access is an alternative implementation method, not an alternative semantics. The semantics of deep access and shallow access are identical. In the shallow-access method, variables declared in subprograms are not stored in the activation records of those subprograms.

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?
Finding the correct activation record instance of a nonlocal variable using static links is relatively straightforward. When a reference is made to nonlocal variable, the activation record instance containing the variable can be found by searching the static chain until a static ancestor activation record instance is found that contains the variable.

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)

Published June 28, 2013 by patriciaivanapurnomo

Lecture: Mr. Tri Djoko Wahjono (D0206)

REVIEW QUESTIONS
1. What are the three general characteristics of subprograms?
– Each subprogram has a single entry point.
– The calling program is suspended during the execution of the called subprogram.
– Control always returns to the caller when the called subprogram’s execution terminates.

8. What are formal parameters? What are actual parameters?
Formal parameter is a dummy variable, which is introduced in the subprogram header, and is used in the function body.
Actual parameter is the value of address used in the statement calling the subprogram.

9. What are the advantages and disadvantages of keyword parameters?
As the names would be the same as the formal parameters, which in their self represent their types and all parameters can appear in any order, so there would be no error with types and type checking. But as we are passing them with their real names, the person who is writing the subprogram should know their real names, which would be a hard deal every now and then.

11. What are the design issues for subprograms?
– Are local variable static or dynamic?
– Can subprogram definitions appear in other subprogram definitions?
– What parameter passing methods are provided?
– Are parameters type checked?
– If subprograms can be passed as parameters and subprograms can be nested, what is the refrencing enviroment of a passed subprogram?
– Can subprograms be overloaded?
– Can subprograms be generic?

12. What are the advantages and disadvantages of dynamic local variables?
Advantages:
– Gives you support for recursion.
– Storage for locals is shared among some subprograms.
Disadvantage:
– Allocation/Deallocation, initialization time
– Indirect addressing(???)
– Subprograms can not be history sensitive

15. What are three semantic models of parameter passing?
– In mode
– Out mode
– Inout mode

16. What are the modes, the conceptual modles of transfer, the advantages, and the disadvantages or pass-by-value, pass-by-result, pass-by-value-result, and pass-by-reference parameter-passing methodes?
pass-by-value:
the value of the actual parameter is used to initialize the corresponding formal parameter. This formal parameter is then used as a local variable in the subprogram. Since the subprogram is receiving data from the actual parameter, this is a model of in-mode semantics. In most cases, pass-by-value is implemented using copy wher an actual value is copied then transmitted. However, it can be implemented by passing an access path to the value of the actual parameter. Copy implementation is more efficient, because when using an access path the value is stored in a write protected cell that is not always simply enforced. An advantage of pass-by-value is it’s speed. Since the actual value is passed there is no need to go find it. A disadvantage is that if a copy is used then that copy must be stored, and that storage could be costly if using a large variable.

pass-by-result:
With pass-by-result, no value is transmitted to the subprogram. Instead, the formal parameter acts like a local variable, and before control is transferred back to the caller the variables value is transmitted back to the actual parameter. Becuase no data is transferred to the subprogram, but it transmits data back to the actual parameter it is an out-mode semantic. Most typically pass-by-result uses a copy conceptual model. Pass-by result hass 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.
void Fixer(out int x, out int y)

Unknown macro: { x=17; y=35; }
f.Fixer(out a, out a);
if x first then a = 35, else if y first then a = 17

pass-by-value-result:
This passing method is actually a combination of pass-by-value and pass-by-result. The value of the actual parameter is used to intialize the corresponding formal parameter, which then acts as a local variable. The formal paramters must have local storage associated with the called subprogram. At termination, the subprogram transmits the value of the formal parameter back to the actual parameter. As such, it uses inout-mode semantics and copy passing conceptual model. Also, 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 (discussed in the pass-by-reference section).

pass-by-reference:
With pass-by-reference an address (reference to the memory location of the actual parameter) is passed to the subprogram. Pass-by-reference is another example of an inout-mode semantic. Also, the reference being passed is an example of an access path conceptual model. An advantage of pass-by-reference is that it is efficient in both time and space. This is no duplicate space required or copying. 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.

19. What are two fundamental design considerations for parameter-passing methods?
First is how much the method is efficient. And second is wether its a one-way or a two-way data transfer. But obviously the collide since the beginning, cause a safe and reliable programming should be using as many one way parameters as possible and to avoid using two ways parameters as long as it can. But the most efficient way is to use pass-by-Refrence which is a two-way passing method.

24. What is an overloaded subprogram?
An overloaded sub program is a sub program that has the same name with another subprogram in the same refrencing enviroment, but has a different protocol.

25. What is ad hoc binding?
The environment of the call statement that passed the subprogram as an actual parameter is called ad hoc binding.

26. What is multicast delegate?
Multicast delegate is the all of the methods stored in a delegate instance are calles in the order in which they were placed in the instance.

30. What are the design issues for functions?
– Are side effects allowed?
– What types of return values are allowed?

37. In what ways are the coroutines different from conventional subprograms?
Coroutines have more than one entry point, where as subprograms have only one.
Coroutines call is named resume.

PROBLEM SET
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: 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 }

6 . Compare and contrast PHP’s parameter passing with that of C#.
PHP’s parameter passing is similar to that of C#, except that either the actual parameter or the formal parameter can specify pass-by-reference. Passby- reference is specified by preceding one or both of the parameters with an ampersand.

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:
list[0] = 3 | list[1] = 5
b. Passed by reference
list[0] = 4 | list[1] = 6
c. Passed by value-result
list[0] = 4 | list[1] = 6

11. Compare the use of closures by programming languages.
Nearly all functional programming languages, most scripting languages, and at least one primarily imperative language, C#, support closures. These languages are static-scoped, allow nested subprograms, and allow subprograms to be passed as parameters.

15. How is the problem of passing multidimensional arrays handled by Ada?
Ada compilers are able to determine the defined size of the dimensions of all arrays that are used as parameters at the time subprograms are compiled.

CONCEPTS OF PROGRAMMING LANGUAGES – CHAPTER 8(STATEMENT-LEVEL CONTROL STRUCTURES)

Published June 28, 2013 by patriciaivanapurnomo

Lecture: Mr. Tri Djoko Wahjono (D0206)

REVIEW QUESTIONS
1. What is definition of control structure?
A control structure is a primary concept in most high-level programming languages. In its simplest sense, it is a block of code. More specifically, control structures are blocks of code that dictate the flow of control. In other words, a control structure is a container for a series of function calls, instructions and statements.

2. What did Bohm and Jocopini prove about flowcharts?
The Bohm-Jacopini proof describes how to construct a structured flow chart from an arbitrary chart, using the bits in an extra integer variable to keep track of information that the original program represents by the program location. This construction was based on Bohm’s programming language P′′. The Bohm-Jacopini proof did not settle the question of whether to adopt structured programming for software development, partly because the construction was more likely to obscure a program than to improve it. On the contrary, it signalled the beginning of the debate. Edsger Dijkstra’s famous letter, “Go To Statement Considered Harmful,” followed in 1968. Subsequent proofs of the theorem addressed practical shortcomings of the Bohm-Jacopini proof with constructions that maintained or improved the clarity of the original program.

3. What is the definition of block?
A block is a section of code which is grouped together. Blocks consist of one or more declarations and statements. A programming language that permits the creation of blocks, including blocks nested within other blocks, is called a block-structured programming language.

9. What are the design issues for multiple-selection statement?
– 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?

12. On what previous language was C’s switch statement based?
ALGOL 68

14. What are design issues for all iterative control statement?
– How is the iteration controlled?
– Where should the control mechanism appear in the loop statement?

15. What are 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. 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 a type of looping structure that is primarily used for data structures. Instead of being controlled by a counter or boolean expression, it is controlled by the number of elements in a data structure. In order to achieve this the user-defined control uses a user-defined frunction called an iterator. This iterator is used to traverse through the data structure and retrieve the elements in whatever order the programmer defines. The for loop fo C based languages can simulate a user defined iteration statement because of it great flexibility.
for (ptr=root; ptr==null; ptr=traverse(ptr))
{
}
Assuming that traverse is a runction that will set ptr to the next desired elment of a data structure, this for loop will begin with root and will continue going through the elements until ptr points to a null element.
Many languages provide predefined iterators which are based on the data structure that they are meant to travers, such as Pearl.
reset $list -> moves the iterator to the 1st element
current($list) -> retrieves the current element of list
next($list) -> moves the iterator to the next element in the data structure.

29. How are iterator implemented in Ruby?
Ruby predefines several iterator methods, such as times and upto for counter-controlled loops, and each for simple iterations of arrays and hashes.

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.

4. What are the limitations of implementing a multiple selector from two-way selectors and gotos?
A multiple selector can be built from two-way selectors and gotos, but the resulting structures are cumbersome, unreliable, and difficult to write and read.

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.