Concepts of Programming Language : Chapter 14

REVIEW QUESTION:

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

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

10. What are the four exceptions defined in the Standard package of Ada?
There are four exceptions that are defined in the default package, Standard:

Constraint_aError

Program_Error

Storage_Error

Tasking_Error

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

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

14. What is the name of all C++ exception handlers?
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?
There are two possible forms of the assert statement:
assert condition;
assert condition : expression;

PROBLEM SET:

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

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

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

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

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

There are several advantages of a linguistic mechanism for handling exceptions, such as that found in Ada, over simply using a flag error parameter in all subprograms. One advantage is that the code to test the flag after every call is eliminated. Such testing makes programs longer and harder to read. Another advantage is that exceptions can be propagated farther than one level of control in a uniform and implicit way. Finally, there is the advantage that all programs use a uniform method for dealing with unusual circumstances, leading to enhanced readability.
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.

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

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

Concepts of Programming Language : Chapter 13

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

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

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

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

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

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

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

8. What is the work of a scheduler?

Scheduler manages the sharing of processors among the tasks.

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

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

16. What is a task descriptor?

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

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

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

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

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

30. What is purpose of an Ada terminate clause?

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

34. What does the Java sleep method do?

Sleep method blocks the the thread.

35. What does the Java yield method do?

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

36. What does the Java join method do?

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

37. What does the Java interrupt method do?

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

55. What is Concurrent ML?

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

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

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

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

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

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

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

PROBLEM SET

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

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

2. What are the different ways to handle deadlock?

– Ignoring deadlock

– Detection

– Prevention

– Avoidance

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

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

 

Concepts of Programming Language : Chapter 12

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.

 

PROBLEM SET

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{
public:

void fly(){

cout << “fly” << endl;
}
};

 

class jet:public class plan{
public:

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.

 

Concpets of Programming Language: Chapter 11

review question

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.

PROBLEM SET

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.*;

 

Concpets of Programming Language: Chapter 10

Review Question

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

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

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

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

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

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

 

4. What 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.

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

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

7.     What is display?

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

10.  Explain the two methods of implementing block?

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

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

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

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

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

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

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

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

 

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.

PROBLEM SET        

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

One very simple alternative is to assign integer values to all variable names used in the program. Then the integer values could be used in the activation records, and the comparisons would be between integer values, which are much faster than string comparisons.

 

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.

 

Concpets of Programming Language: Chapter 9

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.

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

The parameters in the subprogram header are called formal parameters.

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

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

The advantage of keyword parameter is that they can appear in any order in the actual parameter list.

The disadvantage to keyword parameters is that the user of the subprogram must know the names of formal parameters.

6.     What are the design issues for subprograms?

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

 

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

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

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

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

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

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

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

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

22.  What are the design issues for functions?

Two design issues are functions.

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

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

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

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.

PROBLEM SET

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};

4. Suppose you want to write a method that prints a heading on a new output page,  along with a page number that is 1 in the first activation and that increases by 1 with each subsequent activation. Can this be done without parameters and without reference to nonlocal variables in Java? Can it be done in C#?

This can be done in both Java and C#, using a static (or class) data member for the page number.

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. Pass-by 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

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.

 

Concpets of Programming Language: Chapter 8

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.

3. What is the definition of block ?
Block is a sequence of code delimited by either braces or the do and end reserved words.

4. What is/ are the design issue(s) for all selection and iteration control statements ?
Selection :
Two-way :
-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 ?
Multiple-Selection :
-On which type the selector is based ?
Iteration :
-How is the iteration controlled ?
-Where should the control mechanism appear in loop statement?

5. What are the design issues for selection structures ?
-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 ?

6. What is unusual about Python’s design of compound statements ?
Python uses indentation to specify compound statements. For example,
if x > y :
x = y
print “case 1″
equally indent statements are grouped as one compound statement.

7. Under what circumstances must an F# selector have an else clause ?
If the expression returns a value, it must have an else clause

 

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?

ALGOL 68

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.

19. What does the range function in Python do ?
It is used to count loops in Python

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.

PROBLEM SET:

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

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

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

 

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

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