2013-06-27

Programming Language Concept (12)

Book : Concept of Programming Language

Page 570
Review Question

2.   The problems associated with programming using abstract data types are:
• In nearly all cases, the features and capabilities of the existing type are not quite right for the new use.
• The type definitions are all independent and are at the same level.
 
3.   The advantage of inheritance is inheritance offers a solution to both the modification problem posed by abstract data type reuse and the program organization problem. If a new abstract data type can inherit the data and functionality of some existing type, and is also allowed to modify some of those entities and add new entities, reuse is greatly facilitated without requiring changes to the reused abstract data type.
 
4.   Message protocol is the entire collection of methods of an object.
 
6. Describe a situation where dynamic binding is a great advantage over its absence.
- There is a base class, A, that defines a method draw that draws some figure associated with the base class. A second class, B, is defined as a subclass of A. Objects of this new class also need a draw method that is like that provided by A but a bit different. With overriding, we can directly modify B’s draw function. But without it, we either make a specific function in A for B and inherit it.

 
7.   Dynamic dispatch is the third characteristic (after abstract data types and inheritance) of object-oriented programming language which is a kind of polymorhphism provided by the dynamic binding of messages to method definitions.
 
8.   An abstract method is an implemented method which all of descendant class should have and it is included in Building.
An abstract class is  a class that includes at least one abstract method.
 
10.  An inner class is  a nonstatic class that is nested directly in another class.
 
12.  All Smalltalk objects are allocated from the heap and are referenced through reference variables, which are implicitly dereferenced.
 
15.  Smalltalk supports single inheritance; it does not allow multiple inheritance.
 
19.  C++ heap-allocated objects are deallocated using destructor.
 
29.  No Objective-C doesn’t support it. Objective-C only supports single inheritance.
 
31.  The root class in Objective-C is called NSObject
 
38.  Boxing is primitive values in Java 5.0+ which is implicitly coerced when they are put in object context. This coercion converts the primitive value to an object of the wrapper class of the primitive value’s type.
 
49.  Access control in Ruby is different for data than it is for methods. All instance data has private access by default, and that cannot be changed. If external access to an instance variable is required, accessor methods must be defined.
 
Page 572 
Problem Set  
 
2.    In what ways can “compatible “ be defined for the relationship between an overridden method and the overriding method?
Every overriding method must have the same number of parameters as the overridden method and the types of the parameters and the return type must be compatible with those of the parent class.

3.   Compare the inheritance of C++ and Java.
• In Java, all objects are Inherited, either directly or indirectly. While in C++ a class can be defined to stand on its own without an ancestor.
•  The meaning of protected member access specifier is somewhat different in Java. In Java, protected members of a class “A” are accessible in other class “B” of same package, even if B doesn’t inherit from A (they both have to be in the same package).
•  Java uses extends keyword for inheritence. Unlike C++, Java doesn’t provide an inheritance specifier like public, protected or private. Therefore, we cannot change the protection level of members of base class in Java, if some data member is public or protected in base class then it remains public or protected in derived class. Like C++, private members of base class are not accessible in derived class. Unlike C++, in Java, we don’t have to remember those rules of inheritance which are combination of base class access specifier and inheritance specifier.
 
5.    Compare abstract class and interface in Java.
• First and major difference between abstract class and interface is that, abstract class is a class while interface is a interface, means by extending abstract class you can not extend another class because Java does not support multiple inheritance but you can implement multiple inheritance in Java.
• Second difference between interface and abstract class in Java is that you can not create non abstract method in interface, every method in interface is by default abstract, but you can create non abstract method in abstract class. Even a class which doesn’t contain any abstract method can be abstract by using abstract keyword.
• Third difference between abstract class and interface in Java is that abstract class are slightly faster than interface because interface involves a search before calling any overridden method in Java. This is not a significant difference in most of cases but if you are writing a time critical application than you may not want to leave any stone unturned.
• Fourth difference between abstract class vs interface in Java is that, interface are better suited for Type declaration and abstract class is more suited for code reuse and evolution perspective.
• Another notable difference between interface and abstract class is that when you add a new method in existing interface it breaks all its implementation and you need to provide an implementation in all clients which is not good. By using abstract class you can provide default implementation in super class.

 
7.   What is one programming situation where multiple inheritance has a significant disadvantage over interfaces?
A situation when there are two classes derived from a common parent and those two derived class has one child.
 
9.   Give an example of inheritance in C++, where a subclass overrides the superclass methods.
class Enemy{
protected:
int Hp;
public:
void attack(){
cout<<”Enemy Attacks using GUN!!”<<endl;
}
};

class BossEnemy: public Enemy{
public:
void attack(){
cout<<”Boss Enemy attacks using MAGIC!!”<<endl;
}
};

 
10.  Explain one advantage of inheritance.
One of the key benefits of inheritance is to minimize the amount of duplicate code in an application by sharing common  code amongst several subclasses. Where equivalent code exists in two related classes, the hierarchy can usually be  refactored to move the common code up to a mutual superclass. This also tends to result in a better organization of  code and smaller, simpler compilation units.
 
17.  What are the different options for object destruction in Java?
There is no explicit deallocation operator. A finalize method is implicitly called when the garbage collector is about to reclaim the storage occupied by the object.

Programming Language Concept (11)

Book : Concept of Programming Language

Page 519
Review Question
1. What are the two kinds of abstractions in programming languages ?
- Process Abstraction and Data Abstraction

2. Define abstract data type .
- A data structure in the form of a record, but which includes subprograms that manipulate its data.

3. What are the advantages of the two parts of the definition of abstract data type ?
- Increased reliability, Reduces range of code and number of variables which a programmer must be aware when writing / reading part of program. Make name conflict less likely to happen

5. What are the language design issues for abstract data types ?
- ADTs must have a function that allows a user to modify a value inside that data type. Although the method is public, the value itself must be private.

10. What is the use of the Ada with clause ?
- To make the names defined in external packages visible

11. What is the use of the Ada use clause ?
- To eliminate the need for explicit qualification of the references to entities from the named package.

12. What is the fundamental difference between a C++ class and an Ada package ?
- Class must be accessed from an instance of itself while package can be accessed directly.

13. From where are C++ objects allocated ?
- From heap

15. What is the purpose of a C++ destructor ?
- To deallocate heap space the object used.

16. What are the legal return types of a destructor ?
- destructor has no return type

21. What are initializers in Objective-C?
- Constructors that must be explicitly called.

26. Why does Java not have destructors ?
- Because Java has its own implicit garbage collection.

Page 520
Problem Set  
2. Suppose someone designed a stack abstract data type in which the function top returned an access path (or pointer ) rather than returning a copy of the top element. This is not a true data abstraction. Why ? Give an example that illustrates the problem.
- The problem with this is that the user is given access to the stack through the returned value of the “top” function. For example, if p is a pointer to objects of the type stored in the stack, we could have:
p = top(stack1);
*p = 42;
These statements access the stack directly, which violates the principle of a data abstraction.

4. What are the advantages of the nonpointer concept in Java ?
- Variable Access are absolutely defined by the programmer
- No memory leak (i.e. dangling pointers, nameless variables etc)

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


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

2013-06-23

Programming Language Concept (10)

Book : Concept of Programming Language

Page 466
Review Question
1. What is the definition used in this chapter for “simple” subprograms ?
-Subprograms cannot be nested and all local variables are static.


2. Which of the caller of callee saves execution status information ?
-Either can save the execution status

3. What must be stored for the linkage to a subprogram ?
- Execution status information

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

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

10. Define static chain, static_depth, nesting_depth,and chain_offset.
-static chain : a chain of static links that connect certain activation record instances in the stack.
-static_depth : integer associated with a static scope that indicates how deeply it is nested in the outermost scope.
-nesting_depth : difference between static_depth of a subprogram containing reference to x and the static_depth of a subprogram containing the declaration of x.
-chain_offset : number of links to the correct activation record instance

12. How are references to variables represented in the static-chain method ?
-It is represented by static_depth.


Page 467
Problem Set  
1. Show the stack with all activation record instances, including static and dynamic chains, when execution reaches position 1 in the following skeletal program. Assume Bigsub is at level 1.
(page 487)
      -      +--------------------------------------------+ <------ top
     /       !       Dynamic link                     ! --+>----\
    /        !----------------------------------------+---!     !
   B         !       Static link                      ! -----\  !
    \        !----------------------------------------+---!  !  !
     \       !       Return (to C)                    !   !  !  !
      -      !----------------------------------------+---!<-+--/
     /       !       Dynamic link                     ! --+>-!
    /        !----------------------------------------+---!  !
   C         !       Static link                      ! --+>-!
    \        !----------------------------------------+---!  !
     \       !       Return (to A)                    !   !  !
      -      !----------------------------------------+---!<-/
     /       !       Dynamic link                     ! --+>------\
    /        !----------------------------------------+---!       !
   A         !       Static link                      ! --+>------!
    \        !----------------------------------------+---!       !
     \       !       Return (to BIGSUB)               !   !       !
      -      !----------------------------------------+---!<------/
BIGSUB       !       Local variables                  !   !
             +----------------------------------------+---+
6. Although local variables in Java methods are dynamically allocated at the beginning of each activation, under what circumstances could the value of a local variable in a particular activation retain the value of previous activation ?
- If the variable is declared as static. Static modifier is a modifier that makes a variable history – sensitive.

7. It is stated in this chapter that when nonlocal variables are accessed in a dynamic-scoped language using the dynamic chain, variable names must be stored in the activation records with the values. If this were actually done, every nonlocal access would require a sequence of costly string comparisons on names. Design an alternative to these string comparisons that would be faster.
- Using approach that uses an auxiliary data structure called a display. Or, to write variable names as integers. These integers act like an array. So when the activation happens, the comparisons will be faster.

9. The static-chain method could be expanded slightly by using two static links in each activation record instance where the second points to the static grandparent activation record instance. How would this approach affect the time required for subprogram linkage and nonlocal references ?
-Including two static links would reduce the access time to nonlocals that are defined in scopes two steps away to be equal to that for nonlocals that are one step away. Overall, because most nonlocal references are relatively close, this could significantly increase the execution efficiency of many programs.

Programming Language Concept (9)

Book : Concept of Programming Language

Page 436
Review Question
1. What are three general characteristics of subprograms ?
- each subprograms 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 ?
- if it has been called and started execution but the execution is not completed yet.

3. What is given in the header of a subprogram ?
- specifies that the following syntactic unit is a subprogram definition of some particular kind, provides name of the subprogram, optionally specifies a list of parameters

4. What characteristics of Python subprograms sets them apart from those of other languages ?
- function def statements are executable

5. What languages allow a variable number of parameters ?
- C,C++,Perl JavaScript, and Lua

6. What is a Ruby array formal parameter ?
- Substitute of keyword parameter which Ruby does not support

7. What is a parameter profile ? What is a subprogram protocol ?
- Parameter profile contains number, order and types of its formal parameter. Subprogram Protocol is the parameter profile and the return value if it is a function.

8. What are formal parameters ? What are actual parameters ?
- formal parameters are parameters in the subprogram header. Actual parameters are a list of parameters included in subprogram call statements

9. What are the advantages and disadvantages of keyword parameters ?
- The advantage is they can appear in any order in the actual parameter list. The disadvantage is the user must know the names of formal parameters.

10 . What are the differences between a function and a procedure ?
- Functions return values while procedure does not .
- Procedure defines new statements, while function define new user-defined operators.
Problem Set

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

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

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

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

Programming Language Concept (8)

Book : Concept of Programming Language

Page 380
Review Question
1. What is the definition of control structure?
A control structure is a control statement and the statements whose execution it controls

2. What did Böhm and Jocopini prove about flowcharts?
That all algorithms that can be expressed by flowcharts
can be coded in a programming language with only two control statements:
one for choosing between two control flow paths and one for logically controlled
iterations

3. What is the definition of block?
In Ruby, a 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?
• Should the conditional mechanism be an integral part of the exit?
• Should only one loop body be exited, or can enclosing loops also be exited?

5. What are the design issues for selection structures?
a) What is the form and type of the expression that controls the section?
b) Can a single statement, a sequence of statements, or a compound statement be selected?
c) 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

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 ?
-On which type the selector is based ?

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

15. What are the design issues for counter-controlled loop statements ?
-What are the type and scope of the loop variable ?
-Should it be legal for the loop variable or loop parameters to be changed in the loop, and if so, does the change affect loop control ?
-Should the loop parameters be evaluated only once, or once for every iteration ?

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

Page 382
Problem Set
1. What design issues should be considered for two-way selection statements ?
-What is the form and type of the expression that controls the selection ?
-How are the then and else clauses specified ?
-How should the meaning of nested selectors be specified ?
 
2.Python uses indentation to specify compound statements. Give an example in support of this statement.
Example :
if x > y :
x = y
print “case 1″

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

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




2013-06-22

Programming Language Concept (7)

Book : Concept of Programming Language

Page 342
Review Question
1. Define operator precedence and operator associativity.
operator precedence :expression evaluation partially define
the order in which the operators of different precedence levels are evaluated.
operator associativity:When an expression contains two adjacent
occurrences of operators with the same level of precedence, the question of which operator is evaluated first

3.What is a prefix operator?
the operator precede the operands

5. What operator usually has right associativity?
the indices never need to be stored

6. What associativity rules are used by APL?
all operators have the same level of
precedence. Thus, the order of evaluation of operators in APL expressions is
determined entirely by the associativity rule, which is right to left for all operators.

8. Define functional side effect.
A side effectof a function, naturally called a functional side effect,occurs when the function changes either one of its parameters or a global variable. (A global
variable is declared outside the function but is accessible in the function.

44. Define type error.
type erroris the application of an operator to an operand of an inap-propriate type.

45. Define strongly typed.
widely acknowledged as being a highly valuable language characteris-tic

47. What is a nonconverting cast?
extracting the value of a variable of one type and using it as if it were of a different type

48. What languages have no type coercions?
Ada

49. Why are C and C++ not strongly typed?
because both include union types, which are not type checked.

Page 343
Problem Set
1. When might you want the compiler to ignore type differences in an expression?
run time

3.Do you think the elimination of overloaded operators in your favorite language would be beneficial?Why or why not?
no, because operator need to multiply use the operator, so it won’t be hard to use the operator again and again

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?
no, because it partially define the order in which the operators of different precedence levels are evaluated

11. In the Burroughs Extended ALGOL language, matrices are stored as a
single-dimensioned array of pointers to the rows of the matrix, which are
treated as single-dimensioned arrays of values. What are the advantages
and disadvantages of such a scheme?
The advantage of this scheme is that accesses that are done in order of the rows can
be made very fast; once the pointer to a row is gotten, all of the elements of the row can
be fetched very quickly. If, however, the elements of a matrix must be accessed in
column order, these accesses will be much slower; every access requires the fetch of a
row pointer and an address computation from there. Note that this access technique was
devised to allow multidimensional array rows to be segments in a virtual storage
management technique. Using this method, multidimensional arrays could be stored and
manipulated that are much larger than the physical memory of the computer.

15. What are the arguments for and against Head management’s single-size cells and variable-size cells?
Integer values stored in decimal waste storage in binary memory computers, simply as
a result of the fact that it takes four binary bits to store a single decimal digit, but those
four bits are capable of storing 16 different values. Therefore, the ability to store six out
of every 16 possible values is wasted. Numeric values can be stored efficiently on binary
memory computers only in number bases that are multiples of 2. If humans had
developed hands with a number of fingers that was a power of 2, these kinds of problems
would not occur.

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

Programming Language Concept (6)

Book : Concept of Programming Language

Page 312
Review Questions
 1.  What is a descriptor?
A descriptor is the collection of the attributes of a variable.

2. What are the advantages and disadvantages of decimal data types?
The advantages of decimal data types is being able to precisely store decimal values, at least those within a restricted range, which can’t be done with floating-point. And the disadvantages of decimal data types are that the range of values is restricted because no exponents are allowed, and their representation in memory is mildly wasteful.

3. What are the design issues for character sting types?
The two most important design issues that are specific to character string types are the following:
- Should strings be simply a special kind of character array or a primitive type?
- Should strings have static or dynamic length?

4. Describe the three string length options.
- Static length string, the length can be static and set when the string is created.
- Limited dynamic length strings, allow strings to have varying length up to a declared and fixed maximum set by the variable’s definition.
- Dynamic length strings, allow strings to have varying length with no maximum.

8. What are the design issues for arrays?
The primary design issues specific to arrays are the following:
- What types are legal for subscripts?
- Are subscripting expressions in element references range checked?
- When are subscript ranges bound?
- When does array allocation take place?
- Are ragged or rectangular multidimensioned arrays allowed, or both?
- Can arrays be initialized when they have their storage allocated?
- What kinds of slices are allowed,if any?

11.How does JavaScript support sparse arrays?
JavaScript sparse arrays means that the subscript values need not be contiguous.

12. What languages support negative superscripts?
Ruby and Lua

13. What languages support array slices with stepsized?
Phyton, Perl, and Ruby.

14. What array initialization feature is available in Ada that is not available in other common imperative languages?
Ada provides two mechanisms for initializing arrays in the declaration statement: by listing them in the order in which they are to be stored, or by directly assigning them to an index position using the => operator, which in Ada is called an arrow.

23. What is the primary difference between a record and a tuple?
In tuple, the elements are not named.

24. Are the tuples of Phyton mutable?
No, Phyton includes an immutable tuple type.

32. What are the design issues for unions?
The primary design issues that are particular to union types are the following:
- Should type checking be required? Note that any such type checking must be dynamic.
- Should unions be embedded in records?

35. What are the design issues for pointer types?
The primary design issues particular to pointers are the following:
- What are the scope and lifetime of a pointer variable?
- What is the lifetime of a heap-dynamic variable?
- Are pointers restricted as to the type of value to which they can point?
- Are pointers used for dynamic storage management, indirect addressing, or both?
- Should the language support pointer types, reference types, or both?

43. What is a compatible type?
A compatible type is one that either is legal for the operator or is allowed under language rules to be implicitly converted by compiler-generated code to a legal type.

48. What languages have no type coercions?
Ada

Page 314
Problem Set

1. What are the arguments for and against four signed integer sized in Java?
Bytes =1 byte, short = 2 bytes, integer = 4 bytes, long  = 8 bytes. As a result, depending on the domain of the variable required, data types are used.

2. How are negative integers stored in memory?
A negative integer could be stored in sign-magnitude notation, in which the sign bit is set to indicate negative and the remainder of the bit string represents the absolute value of the number. Sign-magnitude notation does not lend itself to computer arithmetic. Most computers now use a notation called twos complement to store negative integers, which is convenient for addition and subtraction.

5. What disadvantages are there in implicit dereferencing of pointers, but only in certain contexts? For example, consider the implicit dereference of a pointer to a record in Ada when it is used to reference a record field.
When implicit dereferencing of pointers occurs only in certain contexts, it makes the language slightly less orthogonal. The context of the reference to the pointer determines its meaning. This detracts from the readability of the language and makes it slightly more difficult to learn.

7. Compare the pointer and reference type variable in C++.
A C++ reference type variable is a constant pointer that’s always implicitly dereferenced.

9. C provides two derived data types both for name and structure type equivalence: struct and union. Makes a study on when to use structtype variables and union type variables.
If all data members of the variables are to be used at once then struct type variables are required, otherwise union type variables should be used.

21. In what way is dynamic type checking better than static type checking?
Static checking reduces programmer flexibility.

22. Explain how the dangling-pointer problem can be removed using the locks-and-keys approach.
In the locks-and-keys approach, pointer values are represented as ordered pairs (key, address), where the key is an integer value. Heap-dynamic variables are represented as the storage for the variable plus a header cell that stores an integer lock value. When a heap-dynamic variable is allocated, a lock value is created and placed both in the lock cell of the heap-dynamic variable and in the key cell of the pointer that is specified in the call to new.