2013-06-27

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.

Programming Language Concept (5)

Book : Concept of Programming Language

Page 235
Review Questions

1.  What are the design issues for names?
The following are the primary design issues for names:
-          Are names case sensitive?
-          Are the special words of the language reserved words or keywords?

2. What is the potential danger of case-sensitive names?
To some people, the problems are about writability and readability. For readability, because names that look very similar in fact denote different entities. For writability, many of the predefined names including both uppercase and lowercase letters.

3. In what way are reserved words better than keywords?
As a language design choice, reserved words are better than keywords because the ability to redefine keywords can be confusing.

4. What is an alias?
Aliases are the variables when more than one variable name can be used to access the same memory location.

6.  State transition diagram is a directed graph. The nodes of a state diagram are labeled with state names. The arcs are labeled with the input characters that cause transitions among the states.

8. What are the two distinct goals of syntax analysis?
First, the syntax analyzer must check the input program to determine whether it is syntactically correct.
When an error is found, the analyzer must produce a diagnostic message and
recover. In this case, recovery means it must get back to a normal state and
continue its analysis of the input program. This step is required so that the
compiler finds as many errors as possible during a single analysis of the input
program. If it is not done well, error recovery may create more errors, or at
least more error messages. The second goal of syntax analysis is to produce a
complete parse tree, or at least trace the structure of the complete parse tree,
for syntactically correct input. The parse tree (or its trace) is used as the basis
for translation.

9.  The differences between top-down and bottom-up parsers:
-    Syntax analyzers are either top-down, meaning they construct left most derivations and a parse tree in top-down order, which mean the tree built from the root downward to the leaves.
-    Bottom-up meaning case they construct the reverse of a rightmost derivation and a parse tree in bottom-up order, which mean the parse tree is built from leaves upward to the root


18. What is left factoring?
This states that a <variable> is either an identifier or an identifier followed by
an expression in brackets (a subscript). These rules clearly do not pass the
pair-wise disjointness test, because both RHSs begin with the same terminal, identi-fier.

20. What is a simple phrases of a sentential form?
simple phrases is just a phrase that takes a single derivation step from its root nonterminal node.

21. What is the handle of a sentential form?
mathematically concise, it provides little help in finding the handle
of a given right sentential for

Page 236
Problem Set
2. What is l-value? Write a statement in C language which gives the compile time error “l-value required”.
The address of a variable is called its l-value.

4. Why is the type declaration of a variable necessary? What is the value range of the int type variable in Java?
because it must include an initial value, byte

5. approaches to building a lexical analyzer:
-    Write a formal description of the token patterns of the language using a descriptive language related to regular expressions. These descriptions are used as input to a software tool that automatically generates a lexical analyzer. There are many such tools available for this. The oldest of these, named lex, is commonly included as part of UNIX systems.
-    Design a state transition diagram that describes the token patterns of the language and write a program that implements the diagram.
-    Design a state transition diagram that describes the token patterns of the language and hand-construct a table-driven implementation of the state diagram.

6.  State transition diagram is a directed graph. The nodes of a state diagram are labeled with state names. The arcs are labeled with the input characters that cause transitions among the states.

8.a.Assuming static scooping, in the following, which declaration of x is the correct one for a reference to x?
b.Repeat part a, but assume dynamic scoping.
(a) i. Sub1
ii. Sub126
iii. Main
(b) i. Sub1
ii. Sub1
iii. Sub1

9.  The differences between top-down and bottom-up parsers:
-    Syntax analyzers are either top-down, meaning they construct left most derivations and a parse tree in top-down order, which mean the tree built from the root downward to the leaves.
–    Bottom-up meaning case they construct the reverse of a rightmost derivation and a parse tree in bottom-up order, which mean the parse tree is built from leaves upward to the root