Concept of Programming Languages – Chapter 15 – Functional Programming Languages


2. What does a lambda expression specify?

Lambda expression specifies the parameters and the mapping of a function.

5. Explain why QUOTE is needed for a parameter that is a data list.

Suppose we have a function that has two parameters, an atom and a list, and the purpose of the function is to determine whether the given atom is in the given list. Neither the atom nor the list should be evaluated, they are literal data to be examined. 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?

Simple list is a list whose problem of membership of a given atom in a given list that does not include sublists.

7. What does the abbreviation REPL stand for?

Abbreviation REPL stands for Read-Evaluate-Print-Loop.

23. What are two ways that ML is fundamentally different from Scheme?

ML is a strongly typed language, whereas Scheme is essentially typeless. ML uses a syntax that is more closely related to that of an imperative language than that of LISP.

24. What is stored in an ML evaluation environment?

Names of all implicitly and explicitly declared identifiers in a program, along with their types.

29. What is a curried function?

Curried function is function curried whose 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.

31. Define reader macros.

Reader macros is a special kind of macro, that are expanded during the reader phase of a LISP language processor.

32. What is the use of the evaluation environment table?

The use of the evaluation environment table is to store the names of all implicitly and explicitly declared identifiers in a program, along with their types.

33. Explain the process of currying.

The process of currying replace a functions 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.

36. What is the use of the tuple data type in F#?

Tuple are used in Python, ML, and F# to allow functions to return multiple values.


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

fun function_name (formal parameters) = expressions.

7. What features make F# unique when compared to other languages?

First, it build on the past functional languages as a functional language. Second, it support virtually all programming methodologies in widespread use today. Third, it is the first functional language that is designed for interoperability with other widely used languages. Fourth, it starts out with an elaborate and well-developed IDE and library of utility software with .NET and its framework.

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.

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


2. When is an exception thrown or raised?

An exception is raised when its associated event occurs.

11. Are there any predefined exceptions in Ada?

Yes there are.

12. What is the use of Suppress pragma in Ada?

Disabling certain run-time checks that are parts of the built-in exceptions.

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

Library container classes.

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

Math library functions.

25. What is the difference between checked and unchecked exceptions in Java?

Exceptions of class Error and RuntimeException and their descendants are called unchecked exceptions. All other exceptions are called checked exceptions. Unchecked exceptions are never a concern of the compiler.

28. What is the purpose of the Java finally clause?

There are some situation in which a process must be executed regardless of whether a try clause throws an exception and regardless of whether a thrown exception is caught in a method. One example of such a situation is a file that must be closed. Another is if the method has some external resource that must be freed in the method regardless of how the execution of the method terminates. This is the purpose of Java finally clause made.

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?

Assert statement use is for defensive programming.

32. What is event-driven programming?

Programming whose 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?

Defining the data and methods that are needed for frames.


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.

Detection of subscript range errors is sometimes required by the language design. For example, Java compilers usually generate code to check the correctness of every subscript expression (they do not generate such code when it can be determined at compile time that a subscript expression cannot have an out-of-range value, for example, if the subscript is a literal). In C, subscript ranges are not checked because the cost of such checking was (and still is) not believed to be worth the benefit of detecting such errors. In some compilers for some languages, subscript range checking can be selected (if not turned on by default) or turned off (if it is on by default) as desired in the program or in the command that executes the compiler.

9. Write a comparative analysis of the throw clause and throws clause of Java.

1) You can declare multiple exception thrown by method in throws keyword by separating them in common e.g. throws IOException, ArrayIndexBoundException etc, while you can only throw one instance of exception using throw keyword e.g. throw new IOException(“not able to open connection”).
2) throws keyword gives a method flexibility of throwing an Exception rather than handling it. with throws keyword in method
signature a method suggesting its caller to prepare for Exception declared in throws clause, specially in case of checked Exception and provide sufficient handling of them. On the other hand throw keyword transfer control of execution to caller by throwing an instance of Exception. throw keyword can also be used in place of return as shown in below example:
 private static boolean shutdown() {
        throw new UnsupportedOperationException(“Not yet implemented”);
as in below method shutdown should return boolean but having throw in place compiler understand that this method will always throw exception .
3) throws keyword cannot be used anywhere exception method signature while throw keyword can be used inside method or static initializer block provided sufficient exception handling as shown in example.
        try {
            throw new Exception(“Not able to initialized”);
        } catch (Exception ex) {
            Logger.getLogger(ExceptionTest.class.getName()).log(Level.SEVERE, null, ex);
worth remembering is that static initalizer block should complete normally.
4) throw keyword can also be used to break a switch statement without using break keyword as shown in below example:
int number = 5;
            case 1:
                throw new RuntimeException(“Exception number 1”);
            case 2:
                throw new RuntimeException(“Exception number 2”);

Concept of Programming Languages – Chapter 13 – Concurrency


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.


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


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



3. Compare the inheritance of C++ and Java.

– In Java, all classes inherit from the Object class directly or indirectly. Therefore, there is always a single inheritance tree of classes in Java, and Object class is root of the tree. In Java, if we create a class that doesn’t inherit from any class then it automatically inherits from Object Class. In C++, there is forest of classes; when we create a class that doesn’t inherit from anything, we create a new tree in forest.

– In Java, members of the grandparent class are not directly accessible.

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

– In Java, methods are virtual by default. In C++, we explicitly use virtual keyword.

Java uses a separate keyword interface for interfaces, and abstract keyword for abstract classes and abstract functions.

– Unlike C++, Java doesn’t support multiple inheritance. A class cannot inherit from more than one class. A class can implement multiple interfaces though.

In C++, default constructor of parent class is automatically called, but if we want to call parametrized constructor of a parent class, we must use Initalizer list. Like C++, default constructor of the parent class is automatically called in Java, but if we want to call parametrized constructor then we must use super to call the parent constructor

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 becauseJava 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 plan{

void fly(){

cout << “fly” << endl;


class jet:public class plan{

void fly()
cout << “Fly! Rocket jet activated!” << endl;

10. Explain one 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 and is also allowed to modify some of those entities and add new entities, reuse is greatly facilitated without requiring change to the reused abstract data type. Programmers can begin with an existing abstract data type and design a modified descendant of it to fit a new problem requirement. Furthermore, inheritance provides a framework for the definition of hierarchies of related classes that can reflect the descendant relationship in the problem space.

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.

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 Languages – Chapter 11 – Abstract Data Types and Encapsulation Constructs


2. Define abstract data type.

data type that satisfies the following conditions:

-The representation of objects of the type is hidden from the program units that use the type, so the only direct operations possible on those objects are those provided in the type’s definition.

-The declarations of the type and the protocols of the operations on objects of the type, which provide the type’s interface, are contained in a single syntactic unit. The type’s interface does not depend on the representation of the objects or the implementation of the operations. Also, other program units are allowed to create variables of the defined type.

8. What is the difference between private and limited private types in Ada?

Limited private is more restricted form and objects of a type that is declared limited private have no built-in operations.

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

With clause makes the names defined in external packages visible; in this case Ada. Text_IO, which provides functions for input of text.

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?

Ada packages are more generalize encapsulations that can define any number of types.

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

The purpose of a C++ desctructor is 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.

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

Destructor has no return types and doesn’t use return statements.

21. What are initializers in Objective-C?

The initializers in Objective-C are constructors.

22. What is the use of @private and @public directives?

The use is to specify the access levels of the instance variables in a class definition.

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?

a “friend” of a given class is allowed access to public, private, or protected data in that class. Normally, function that is defined outside of a class cannot access such information.

Class that can access the private and protected members of the class in which it is declared as a friend. On declaration of friend class all member function of the friend class become friends of the class in which the friend class was declared.

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.


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

Any task that would require arrays, structures, and pointers in C can be more easily and reliably performed by declaring objects and arrays of objects. Instead of complex pointer manipulation on array pointers, you access arrays by their arithmetic indices. The Java run-time system checks all array indexing to ensure indices are within the bounds of the array. You no longer have dangling pointers and trashing of memory because of incorrect pointers, because there are no pointers in Java.

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

It will be made automatically by the built-up in.

10. Which two conditions make data type “abstract” ?

– The representation, or definition, of the type and the operations are contained in a single syntactic unit

– The representation of objects of the type is hidden from the program units that use the type, so only direct operations possible on those objects are those provided in the type’s definition

17. The namespace of the C# standard library, System, is not implicitly available to C# programs. Do you think this is a good idea? Defend your answer.

I think it is not, because it reduces its efficiency.

19. Compare Java’s packages with Ruby’s modules.

In Ruby, the require statement is used to import a package or a module. For example, the extensions package/module is imported as follows.

require 'extensions'

External files may be included in a Ruby application by using load or require. For example, to include the external file catalog.rb, add the following require statement.

require "catalog.rb"

The difference between load and require is that load includes the specified Ruby file every time the method is executed and require includes the Ruby file only once.

In Java, the import statement is used to load a package. For example, a Java package java.sql is loaded as follows.

import java.sql.*;

Concept of Programming Languages – Chapter 10 – Implementing Subprograms


4. What is the task of a linker?

Task of a linker 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.

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

-The compiler must generate code to cause the implicit allocation and deallocation of local variables.

-Recursion adds the possibility of multiple simultaneous activations of a subprogram, which means that there can be more than one instance (incomplete execution) of a subprogram at a given time, with at least one call from outside the subprogram and one or more recursive calls. The number of activations is limited only by the memory size of the machine. Each activation requires its activation record instance.

15. Explain the two methods of implementing blocks.

– Blocks can be implemented by using the static-chain process for implementing nested subprograms. Blocks are treated as parameterless subprograms that are always called from the same place in the program. Therefore, every block has an activation record. An instance of its activation record is created every time the block is executed.

– Blocks 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 execution of a program can be statically determined, because blocks are entered and exited in strictly textual order. This amount of space can be allocated after the local variables in the activation record. Offsets for all block variables can be statically computed, so block variables can addressed exactly as if they were local variables.

16. Describe the deep-access method of implementing dynamic scoping.

The dynamic chain links together all subprogram activation recor5s instances in the reverse of the order in which they were activated. Therefore, the dynamic chain is exactly what is needed to reference nonlocal variables in a dynamic-scoped language.

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.


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?

The nesting of scopes is known at compile time, the compiler can determine not only that a reference is nonlocal but also the length of the static chain that must be followed to reach the activation records instance that contains the nonlocal object.

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?

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


Concept of Programming Languages – Chapter 9 – Subprograms


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?

It means that after having been called, a subprogram has begun execution but has not yet completed that execution.

7. What is a parameter profile? What is a subprogram protocol?

Parameter profile is the number, order, and types of its formal parameters.

Subprogram protocol is its parameter profile plus, if it is a function, its return type. In languages in which subprograms have types, those types are defined by the subprogram’s protocol.

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

Formal parameters are the parameters in the subprogram header.

Actual parameters are a list of parameters to be bound to the formal parameters of the subprogram which must be included with the name of the subprogram by the subprogram call statements.

10. What are the differences between a function and a procedure?

Functions return values and procedures do not.

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

-They can do both.

Simply: in mode, out mode, and inout mode.

17. Describe the ways that aliases can occur with pass-by-reference parameters.

Pass by reference makes access paths available to the called subprograms, thereby providing access to non-local variables. These are the ways:

First, collisions can occur between actual parameters. Consider a C++ function that has two parameters that are to be passed by reference, as in

void fun(int &first, int &second)

If the call to fun happens to pass the same variable twice, as in

fun(total, total)

the first and second in fun will be aliases

Second, collisions between array elements can also cause aliases. For example, suppose the function fun is called with two array elements that are specified with variable subscripts, as in

fun(list[i], list[j])

If these two parameters are passed by reference and i happens to be equal to j, then first and second are again aliases.

Third, if two of the formal parameters of a subprogram are an element of an array and the whole array, and both are passed by reference, then a call such as

fun1(list[i], list)

could result in aliasing in fun1, because fun1 can access all elements of list through the second parameter and access a single element through its first parameter.

Still another way to get aliasing with pass-by-reference parameters is through collisions between formal parameters and non-local variables that are visible.

24. What is an overloaded subprogram?

Overloaded subprogram is a subprogram that has the same name as another subprogram in the same referencing environment. Every version of an overloaded subprogram must have a unique protocol; that is, it must be different from the others in the number, order, or types of its parameters, and possibly in its return type if it is a function.

26. What is multicast delegate?

Multicast delegate is all of the methods stored in a delegate instance are called in the order in which they were placed in the instance.

32. What exactly is a delegate?

A delegate is the power and flexibility of method pointers in C# increased by making them objects.


1. Consider the following program written in C syntax:

void swap(int a, int b)
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 = 2;

list[5] = {4, 1, 2, 8, 10};

c. Passed by value-result

value = 2;

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

3, 5

b. Passed by reference

6, 10

c. Passed by value-result

6, 10

14. Speculate on the issue of allowing function or method overloading in some programming languages. Why are the not allowed by many contemporary languages?

Because it is concerned to lead to ambiguity and some error compilation.

15. How is the problem of passing multidimensional arrays handled by Ada?

In Ada, unconstrained array types can be formal parameters. An unconstrained array type is one in which the index ranges are not given in the array type definition. Definitions of variables of unconstrained array types must include index ranges. The code in subprogram that is passed an unconstrained array can obtain the index range information of the actual parameter associated with such parameters.

Concept of Programming Languages – Chapter 8 – Statement-Level Control Structures


1. What is the definition of control structure?

Control structure is a control statement and the colletion of statements whose execution it controls.

2. What did Bohm and Jocopini prove about flowchart?

They proved that all algortihms 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.

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

The design issues are what the the form and type of the expression that controls the selection is, how the selectable segments specified are, whether execution flow through the structure is restricted to include just a single selectable segment or not, how the case value are specified, and how unrepresented selector expression values should be handled if at all.

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


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

The design issues are how the iteration is controlled and where the control mechanism should appear in the loop statement.

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

The design issues for counter-controlled loop statement are what the type and scope of the loop variable are, whether it should be legal for the loop variable or loop parameters to be changed in the loop and if so, whether the change affects loop control or not, and if the lop parameters should be evaluated only once or once for every iteration.

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

Pretest loop statement is used to mean that the rest for loop completion occurs before the loop body is executed.

Posttest loop statement is used to mean that it occurs after the loop body is executed.

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

The design issues are whether the control should be pretest/posttest and whether the logically controlled loop should be a special form of a counting loop or a separate statement.

22. What is the main reason user-located loop control statements were invented?

The main reason user-located loop control statement were invented is to choose a location for loop control other than the top or bottom of the loop body.

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

The design issues are whether the conditional mechanism should be an integral part of the exit or not & whether only loop body should be exited or enclosing loops can also be exited.


1. What design issues should be considered for two-way selection statements?

-What the form and type of the expression that controls the selection is.

-How the then and else clauses are specified.

– How the meaning of nested selectors should be specified.

2. Python uses indentation to specify compound statements. Give an example in support of this statement.

def perm(l):
        # Compute the list of all permutations of l
    if len(l) <= 1:
                  return [l]
    r = []
    for i in range(len(l)):
             s = l[:i] + l[i+1:]
             p = perm(s)
             for x in p:
              r.append(l[i:i+1] + x)
    return r

3. 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 is usually more compact than lots of nested if else and therefore, more readable
  • If you omit the break between two switch cases, you can fall through to the next case in many C-like languages. With if else you’d need a goto (which is not very nice to your readers … if the language supports goto at all).
  • In most languages, switch only accepts primitive types as key and constants as cases. This means it can be optimized by the compiler using a jump table which is very fast.
  • It is not really clear how to format switch correctly. Semantically, the cases are jump targets (like labels for goto) which should be flush left. Things get worse when you have curly braces:
    case XXX: {
    } break;

    Or should the braces go into lines of their own? Should the closing brace go behind the break? How unreadable would that be? etc.

  • In many languages, switch only accepts only some data types.


  • if allows complex expressions in the condition while switch wants a constant
  • You can’t accidentally forget the break between ifs but you can forget the else (especially during cut’n’paste)
  • it accepts all data types.


Generally both of them have the same concept but when you have more than one option including some condition, it is suggested to use if-else rather than switch. Because switch only accepts primitive types as key and constants as cases.

Concepts of Programming Languages – Chapter 7 – Expressions and Assignment Statements


2. What is a ternary operator?

Ternary operator is operator that has three operands.

3. What is a prefix operator?

Prefix operator is operator that precedes operands.

9. What is a coercion?

Coercion is an implicit type conversion that is initiated by the compiler.

11. What is an overloaded operator?

Overloaded operator is operator that has multiple use.

12. Define narrowing and widening conversions.

Narrowing conversion converts a value to a type that cannot store even approximations of all of the values of the original type.

Widening conversion converts a value to a type that can include at least approximations of all the values of the original type.

18. What is short-circuit evaluation?

Short-circuit evaluation is one in which the result is determined without evaluating all of the operands and/or operators.

19. What mixed-mode assignments are allowed in Java?

Mixed-mode assignment allowed in Java is assigning int value to a float variable, but not vice versa, if the required coercion is widening.


3. Do you think the elimination of overloaded operators in your favorite language would be  beneficial? Why or why not?

As I have learned C / C++ only, which is quite similar for the syntax although different orientation (C++ is object-oriented programming), I think elimination of overloaded operators wouldn’t be beneficial. Because it has been the way it is, I can imagine if we would change for an instance the use of * as pointer and multiplication, either of the use of operator that would be eliminated and changed will have to need a new operand and it causes too much operands with a slight use.

4. Would it be a good idea to eliminate all operator precedence rules and require parentheses to show the desired precedence in expressions? Why or why not?

It wouldn’t be a good idea to eliminate all operator precedence rules and require parentheses to show the desired precedence in expressions, because the precedence rules has been a good implementation of mathematics operations rules we do in math. So if we eliminate it, it will make a different rule of mathematics operation due to the elimination of precedence rule and it would be troublesome if we have give parentheses to show precedence in expressions while in fact we’ve already learned in math about the precedence of those operators.

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

Yes C should! Because those assigning operations make operation simpler and easy to know if that operation is assigning operation.

6. Should C’s single-operand assignment forms (for example, ++count) be included in other languages (that do not already have them)? Why or why not?

Yes C should, because it will ease the increment or even decrement while we use in looping rather than manually by the assigning, and also by using that we can easily know that it is not operation, instead it is an increment or decrement which is usually used in repetition.

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

It wouldn’t be commutative when it deals with the negative integers. Recall that we can consider subtraction as addition in which one of two operator is a negative integer.

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

It is not associative when it includes the other operator with higher precedence like the multiplication and division.

Concepts of Programming Languages – Chapter 6 – Data Types


1. What is a descriptor?

A descriptor is the collection of the attributes of a variable. In a implementation, a descriptor is an area of memory that stores the attributes of a variable. If the attributes are all static, descriptors are required only at compile time. These descriptors are built by the compiler, usually as a part of the symbol table, and are used during compilation. For dynamic attributes, however, part or all of the descriptor must be maintained during execution. In this case, the descriptor is used by the run-time system. In all cases, descriptors are used for type checking and building the code for the allocation and deallocation operations.

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

The advantages is being able to precisely store decimal values, at least those within a restricted range, which cannot be done with floating-point. The disadvantages are that that the range of value is restricted because no exponents are allowed, and their representation in memory is mildly wasteful.

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

The design issues for character string types are if string should be simply a special kind of character array or a primitive type and if string should have static or dynamic length.

4. Describe the three string length options.

Static length string: the length that can be static and set when the string is created. This is the choice for strings of Pyhthon, the immutable objects of Java’s string class, as well as similar classes in the C++ standard class library, Ruby’s built-in string class,  and the .NET class library available to C# and F#.

Dynamic length strings: string length which is used to allow string to have varying length up to a declared and fixed maximum set by the variable’s definition, as exemplified by the strings in C and the C-style st5rings of C++. Such string variables can store any number of characters between zero and the maximum. Recall that strings in C, se a special character to indicate the end of the string’s characters, rather than maintaining the string length.

Dynamic length strings: string which is used to allow strings to have varying length with no maximum, as in JavaScript, Perl,  and the standard C++ library. It requires the overhead of dynamic storage allocation and deallocation but provides maximum flexibility.

5. Define ordinal, enumeration, and subrange types.

Ordinal type is one in which the age of possible values can be easily associated with the set of positive integers. In Java, for example, the primitive ordinal types are integer, char, and boolean.

Enumeration and subrange are the two user-defined ordinal type that have been supported by the programming languages.

Enumeration type is one in which all of the possible values, which are named constants, are provided, or enumerated, in the definition. Enumeration types provide a way of defining and grouping collections of named constants, which are called enumeration constants.

Subrange type is a contiguous subsequence of an ordinal type.

8. What are the design issues for arrays?

The design issues for arrays are what types legal for subscripts are, of subscripting expression ins element references range checked, when subscript range bound are, when array allocation takes place, if ragged or rectangular multidimensioned arrays allowed or both, if arrays can be initialized when they have their storage allocated, what kinds of slices are allowed if any.

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

Static array is one in which the subscript ranges are statically bound and storage allocation is static (done before run time). The advantages of static arrays is efficiency. No dynamic allocation or deallocation is required. The disadvantage is that the storage for the array is fixed for the entire execution time of the program.

A fixed stack-dynamic array is one in which the subscript ranges are statically bound, but the allocation is done at declaration elaboration time during execution. The advantage of it over the static array is space efficiency. A large array in one subprogram can use the same space as a largae array in a different subprogram, as long as both subprograms are not active at the same time. The same is true if the two arrays are in different blocks that are not active at the same time. The disadvantages is the required allocation and deallocation time.

A stack-dynamic array is one in which both the subscript ranges and the storage allocation are dynamically bound at elaboration time. Once the subscript ranges are bound and the storage is allocated, however, they remain fixed during the lifetime of the variable. The advantage of stack-dynamic arrays over static and fixed stack-dynamic array is flexibility. The size of an array need not be known until the array is about to be used.

A fixed heap-dynamic array is similar to a fixed stack-dynamic array, in that subscript ranges and the storage binding are both fixed after storage is allocated. The differences are 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 advantages of fixed heap-dynamic arrays is flexibility – the array’s size always fits the problem.

A heap-dynamic array is one in which the binding of subscript ranges and storage allocation is dynamic and can change any number of times during the array’s lifetime. The advantage of heap-dynamic arrays over the others is the flexibility: Arrays can grow and shrink during program execution as the need for space changes.

17. Define row major order and column major order.

Row major order: 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. If the array is a matrix, it is stored  by rows.

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. If the array is a matrix, it is stored by columns.

22. Define fully qualified and elliptical references to fields in records.

Fully qualified reference to fields in records is one in which all intermediate record names, from the larges enclosing record to  the specific field, are named in the reference.

Elliptical references to fields in records is when the field is named, but any or all of the enclosing record names can be omitted, as long as the resulting reference is unambiguous in the referencing environment.

24. Are the tuples of Python mutable?

No, they aren’t.

25. What is the purpose of an F# tuple pattern?

The purpose is to allow functions to return multiple values.

27. What is the action of the scheme function CAR?

The CAR function returns the first element of its list parameter.

35. What are the design issues for pointer types?

The design issues for pointer types are what the scope and lifetime of a pointer variable are, what the lifetime of a heap-dynamic variable (the value a pointer references) is, if pointers are restricted as to the type of value to which they can point, if pointers are used for dynamic storage management, indirect addressing, or both, and if the language should support pointer types, reference type, or both.

44. Define type error.

Type error is the application of an operator to an operand of an inappropriate type.

45. Define strongly typed.

A programming language is strongly typed if type errors are always detected. This requires that the type of all operand can be determined, either at compile time or at run time. The importance of it lies in its ability to detect all misuses of variables that result in type error. It also allows the detection, at run time, of uses of the incorrect type value in variables that can store values of more than one type.


1. What are the arguments for and against four signed integer sizes in Java?

Arguments for and against four signed integer sizes in Java are byte, short, int, and long.

2. How are negative integers stored in memory?

Negative integers are stored in memory by using a notation called twos complement to store negative integers, which is convenient for addition and subtraction. In twos-complement notation, the representation of a negative integer is formed by taking the logical complement of the positive version of the number and adding one.

3. The collection of values that can be represented by a floating-point type is defined in terms of precision and range. What are precision and range? Show the IEEE Floating-Point standard 754 format for single- and double- precision representation.

Precision is the accuracy of the fractional part of a value, as the number of bits.

Range is a combination of the range of the fraction, more important, the range of exponents.

IEEE Floating-Point standard 754 format for single-representation.

[sign bit][Exponent (8bits)] Fraction (23bits)]

IEEE Floating-Point standard 754 format for double-representation.

[sign bit][Exponent (11bits)] Fraction (52bits)]

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.

We use struct type variable when members are laid out one after each other (with optional padding in between). We use union type variable when members overlay the memory of each other so that the sizeof of a union is the one .

19. Any type define with typedef is type equivalent to its parent type. How does the use of typedef differ in C and C++?

The use of typedef differs in C and C++ that C uses name type equivalence for structure, enumerations, and unions is if two structures, enumeration, or unions are defined in different files, in which case structural type equivalence is used. This is a loophole int the name type equivalence rule to allow equivalence of structures, enumerations, and unions that are defined in different files.

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

Dynamic type checking is better than static type checking in way of a language allowing a memory cell to store values of different types at different times during execution. Such memory cells can be created with Ada variant records, C and C++ unions, and the discriminated unions of ML, Haskell, and F#.  In these cases,  type checking, if done,  must be dynamic and requires the run-time system to maintain the type of the current value of such memory cells. So, even though all variables are statically bound to types in languages such as C++, not all type errors can be detected by static type checking.