Rabu, 17 Desember 2014

CHAPTER 9

Nama : Aditya Isnugraha
Class   : LM01
NIM    : 1801419606

Assignment from Tri Djoko Wahjono
CHAPTER 9

- REVIEW QUESTIONS
11. What are the design issues for subprograms? 
Answer :
The design issues for subprograms are:

- Are local variables statically or dynamically allocated?

- Can subprogram definitions appear in other subprogram definitions?

- What parameter-passing method or methods are used?

- Are the types of the actual parameters checked against the types of the

formal parameters?

- If subprograms can be passed as parameters and subprograms can be nested,

what is the referencing environment of a passed subprogram?

- Can subprograms be overloaded?

- Can subprograms be generic?

- If the language allows nested subprograms, are closures supported?

 
12. What are the advantages and disadvantages of dynamic local variables?
Answer :

There are several advantages of stack-dynamic local variables, the primary one being the flexibility they provide to the subprogram. It is essential that recursive subprograms have stack-dynamic local variables. Another advantage of stack-dynamic locals is that the storage for local variables in an active subprogram can be shared with the local variables in all inactive subprograms.

The main disadvantages of stack-dynamic local variables are the following:

First, there is the cost of the time required to allocate, initialize (when necessary), and deallocate such variables for each call to the subprogram. Second, accesses to stack-dynamic local variables must be indirect, whereas accesses to static variables can be direct. This indirectness is required because the place in the stack where a particular local variable will reside can be determined only during execution. Finally, when all local variables are stack dynamic, subprograms cannot be history sensitive; that is, they cannot retain data values of local variables between calls.
 



13. What are the advantages and disadvantages of static local variables?
Answer :
The primary advantage of static local variables over stack-dynamic local variables is that they are slightly more efficient—they require no run-time overhead for allocation and deallocation. Also, if accessed directly, these accesses are obviously more efficient. And, of course, they allow subprograms to be history sensitive. The greatest disadvantage of static local variables is their inability to support recursion. Also, their storage cannot be shared with the local variables of other inactive subprograms.



14. What languages allow subprogram definitions to be nested? 
Answer :

For a long time, the only languages that allowed nested subprograms were those directly descending from Algol 60, which were Algol 68, Pascal, and Ada. JavaScript, Python, Ruby, and Lua are also, most functional programming languages allow subprograms to be nested.
 



15. What are the three semantic models of parameter passing?
Answer :
 Formal parameters are characterized by one of three distinct semantics models:

(1) They can receive data from the corresponding actual parameter; (2) they can transmit data to the actual parameter; or (3) they can do both. These models are called in mode, out mode, and inout mode, respectively.


- PROBLEM SET

11. C# supports out-mode parameters, but neither Java nor C++ does. Explain the difference. 
Answer :



12. Research Jensen’s Device, which was a widely known use of pass-by- name parameters, and write a short description of what it is and how it can be used. 
 Answer :
 Implementing a pass-by-name parameter requires a subprogram to be passed to the called subprogram to evaluate the address or value of the formal parameter. The referencing environment of the passed subprogram must also be passed. This subprogram/referencing environment is a closure. Pass-by-name parameters are both complex to implement and inefficient. They also add significant complexity to the program, thereby lowering its readability and reliability. Because pass-by-name is not part of any widely used language, it is not discussed further here. However, it is used at compile time by the macros in assembly languages and for the generic parameters of the generic subprograms in C++, Java 5.0, and C# 2005.


13. Study the iterator mechanisms of Ruby and CLU and list their similari- ties and differences.
 Answer :



14. Speculate on the issue of allowing nested subprograms in programming languages—why are they not allowed in many contemporary languages? 
 Answer :
 Because it is concerned to lead to ambiguity and some error compilation.


15. What are at least two arguments against the use of pass-by-name parameters? 
Answer :
 Ada compilers are able to determine the defined size of the dimensions of all arrays that are used as parameters at the time subprograms are compiled. 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 a subprogram that is passed an unconstrained array can obtain the index range information of the actual parameter associated with such parameters
About these ads
Share this:

CHAPTER 8

Nama : Aditya Isnugraha
Class   : LM01
NIM    : 1801419606

Assignment from Tri Djoko Wahjono
CHAPTER 8

- REVIEW QUESTION

11. What is unusual about C’s multiple-selection statement? 
Answer :
 the C switch statement has virtually no restrictions on the placement of the case expressions, which are treated as if they were normal statement labels. This laxness can result in highly complex structure eithin the switch body.



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




13. Explain how C#’s switch statement is safer than that of C. 
Answer :
 C# has a static semantics rule that disallows the implicit execution of more than one segment. Every segment must end with an explicit unconditional branch statement which transfer control out of the switch statement, or a goto, which can transfer control to one of the selectable segments


14. What are the design issues for all iterative control statements? 
Answer :
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 statements? 
Answer :
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.





- PROBLEM SET

10. In Ada, the choice lists of the case statement must be exhaustive, so that there can be no unrepresented values in the control expression. In C++, unrepresented values can be caught at run time with the default selec- tor. If there is no default, an unrepresented value causes the whole statement to be skipped. What are the pros and cons of these two designs (Ada and C++)? 
Answer :
Ada was designed for military grade software development. The idea is that whenever you modify code in such a way that a new case emerges (for example adding a new value for an enumeration type), you are forced to manually revisit (and therefore re-validate) all the case statements that analyze it. Having a "default" is risky: you may forget that there is a case somewhere where the new case should not have been handled by the default. 

 
11. Explain the advantages and disadvantages of the Java for statement, compared to Ada’s for. 
 Answer :
 Java’s variable in the argument of a switch statement can be of integeral type (byte, short, int, etc), char, and String (JDK 1.7 and newer versions), but C++ can only be int or char.


12. Describe a programming situation in which the else clause in Python’s for statement would be convenient. 
 Answer :



13. Describe three specific programming situations that require a posttest loop. 
 Answer :



14. Speculate as to the reason control can be transferred into a C loop statement.

Answer :
 goto statements can be used to have one cleanup sction in routine rather than multiple return statements, or used to exit out a nested loop that is very long


Rabu, 26 November 2014

CHAPTER 7

Nama : Aditya Isnugraha
Class   : LM01
NIM    : 1801419606

Assignment from Tri Djoko Wahjono
CHAPTER 7

- REVIEW QUESTION

11. What is an overloaded operator? 
Answer :
 Operator that has different implementation depending on its arguments.


12. Define narrowing and widening conversions. 
Answer :
 Widening conversion is a conversion that converts a value to a type that can include least approximations of all values of the original type. Narrowing conversion is a conversion of data that might cause a loss of precision



13. In JavaScript, what is the difference between == and ===? 
Answer :
“==” operator is known as type coercion operator and anytime if both values are same and compared using ==operator, type coercion happens. On the other hand === is known as strictly equality operator. It’s much similar Java’s equality operator (==), which gives compilation error if you compare two variables, whose types are not compatible to each other.


14. What is a mixed-mode expression? 
Answer :
 Mixed-mode expression: The expressions that allow them to design decisions concerning arithmetic expressions is whether an operator can have operands of different types.


15. What is referential transparency?
 Answer :
two expressions in the program that have the same value can be substituted for one
another anywhere in the program, without affecting the action of the program







 - PROBLEM SET

11. Write a BNF description of the precedence and associativity rules defined for the expressions in Problem 9. Assume the only operands are the names a,b,c,d, and e. 
Answer :
 <expr> → <expr> or <e1> | <expr> xor <e1> | <e1>

<e1> → <e1> and <e2> | <e2>

<e2> → <e2> = <e3> | <e2> /= <e3> | <e2> < <e3>

| <e2> <= <e3> | <e2> > <e3> | <e2> >= <e3> | <e3>

<e3> → <e4>

<e4> → <e4> + <e5> | <e4> – <e5> | <e4> & <e5> | <e4> mod <e5> | <e5>

<e5> → <e5> * <e6> | <e5> / <e6> | not <e5> | <e6>

<e6> → a | b | c | d | e | const | ( <expr> )


12. Using the grammar of Problem 11, draw parse trees for the expressions of Problem 9. 
Answer :



13. Let the function fun be defined as
int fun(int *k) {  

*k += 4;  
return 3 * (*k) - 1; 
}
Suppose fun is used in a program as follows:
void main() {  

int i = 10, j = 10, sum1, sum2;  
sum1 = (i / 2) + fun(&i);  
sum2 = fun(&j) + (j / 2); }

What are the values of sum1 and sum2 

a. if the operands in the expressions are evaluated left to right? 
b. if the operands in the expressions are evaluated right to left?
Answer :
(a) (left -> right)

sum 1 = 46
sum 2 = 48

(b) (right -> left)

sum 1 = 48
sum 2 = 46


14. What is your primary argument against (or for) the operator precedence rules of APL? 
Answer :
 The operator precedence rules of the common imperative languages are nearly all the same, because they are based on those of mathematics.


15. Explain why it is difficult to eliminate functional side effects in C.
Answer :
One reason functional side effects would be difficult to remove from C is that all of C’s subprograms are functions, providing the ability of returning only a single data value.












Rabu, 05 November 2014

CHAPTER 6

Nama : Aditya Isnugraha
Class   : LM01
NIM    : 1801419606

Assignment from Tri Djoko Wahjono
CHAPTER 6

- REVIEW QUESTION

10. What happens when a nonexistent element of an array is referenced in Perl?
       Answer :
If you try to append non-existent elements from an array to another one, the initial array will grow as needed, even though the elements to append do not exist.


11. How does JavaScript support sparse arrays?
      Answer :
JavaScript objects are sparse, and arrays are just specialized objects with an auto-maintained length property (which is actually one larger than the largest index, not the number of defined elements) and some additional methods.


12. What languages support negative subscripts?
      Answer : Ruby and Lua support negative subscripts.



13. What languages support array slices with Stepsizes?
      Answer : Ruby, Python, Perl.



14. What array initialization feature is available in Ada that is not available in other common imperative languages?
       Answer :
Ada provides two mechanisms for initializing arrays in the declarations statements: 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.


15. What is an aggregate constant?
       Answer : A parenthesized lists of values.

 
- PROBLEM SET


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?
      Answer :
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.


12. Analyze and write a comparison of C’s malloc and free functions with C++’s new and delete operators. Use safety as the primary consider- ation in the comparison.
      Answer :  new and delete are type safe (no need for casts), malloc and free are not. Also malloc returns a void* which then has to be cast to the appropriate pointer type. new returns the correct pointer type itself;  type safety.  malloc requires you to tell the number of bytes to allocate,  new figures it out itself.



13. Analyze and write a comparison of using C++ pointers and Java reference variables to refer to fixed heap-dynamic variables. Use safety and conve- nience as the primary considerations in the comparison.
      Answer :
 -In c and C++ pointer can be use the same way as addresses. This design offer
no solutions to the dangling pointer or lost heap-dynamic variable problems.
-Reference types, such as those in Java and C#, provide heap management
without the dangers of pointers.
so it's clear that Java has more safety for the heap-dynamic variables.


14. Write a short discussion of what was lost and what was gained in Java’s designers’ decision to not include the pointers of C++.
      Answer :
There's a copious amount of documentation out there on this subject so there's no reason to write at length. I should also point out that pointers are a feature of both C and C++.

It's obvious that preventing the use of pointers significantly bolstered the amount of security that programmers could get 'for free' given that issues like stack overruns, memory corruption and inadequate/incorrect freeing of memory (though this is more an attribute of GC than lack of pointers) were largely nullified.

Given that programmers tend to be kind of ornery and resistant to change, preventing a means for direct memory access and easy manipulation of the data within rubbed a lot of programmers the wrong way. Many pointed out that the use of pointers was one of the ways that C/C++ were able to be such a high-level language while still maintaining considerable speed. While assembly language and machine code were still de rigeur amongst people that were looking to squeeze the most amount of speed and memory out of a given program, things like pointers and compilers that effectively optimized C and C++ code did a lot to win people over, not to mention that it's a hell of a lot easier to read.

With Java, however, a lot of those same programmers felt that the security that was gained was offset by the decreases in speed and the fact that a lot of the earlier JIT compilers were pretty pokey didn't help that. For all their faults, Sun's been pretty adamant about listening to the community so they've made a lot of improvements regarding in-place optimization, HotSpot, conditional compilation, etc.

Another problem that came about is the fact that removing pointers made existing C and C++ code hard to port. That's generally pretty true of any new or significantly changed language, however. Eventually people got a handle on how to best replicate pointer usage, tips and tricks got passed around and things improved..
  


15. What are the arguments for and against Java’s implicit heap stor- age recovery, when compared with the explicit heap storage recovery required in C++? Consider real-time systems.
      Answer :
Implicit eliminates the creation of dangling pointers. Disadv: cpu-time to do recovery, sometimes when there’s plenty of heap storage so recovery isn’t necessary.










Rabu, 29 Oktober 2014

CHAPTER 5

Nama : Aditya Isnugraha
Class   : LM01
NIM    : 1801419606

Assignment from Tri Djoko Wahjono
CHAPTER5

- REVIEW QUESTION

11. What are the advantages and disadvantages of dynamic type binding?
Answer :
Advantages: flexibility and no definite types declared(PHP, JavaScript).

Disadvantages: adds to the cost of implementation and type error detection by the compiler is difficult.



12. Define static, stack-dynamic, explicit heap-dynamic, and implicit heap- dynamic variables. What are their advantages and disadvantages?
Answer :
- Static: bound to memory cells before execution begins and remains bound to the same memory cell throughout the execution.

- Stack-dynamic: storage bindings are created for variables when their declaration statements are elaborated.

- Explicit heap-dynamic: allocated and deallocated by explicit directives, specified by the programmer, which take effect during execution.

- Implicit heap-dynamic variables: Allocation and deallocation caused by assignment statements.


13. Define lifetime, scope, static scope, and dynamic scope.
Answer :
 - Lifetime: A time during which the variable is bound to a specific memory location. The lifetime begins when it is bound to a specific cell and ends when it is unbound from that cell.
 - Scope: The range of statements in which the variable is visible. A variable is visible in a statement if it can be referenced in that statement.
 - Static scope: is based on program text and to connect a name reference to a variable , you (or the compiler) must find the declaration.
 - Dynamic scope: Based on calling sequences of program units, not their textual layout (temporal versus spatial). References to variables are connected to declarations by searching back through the chain of subprogram calls that forced execution to this point.



14. How is a reference to a nonlocal variable in a static-scoped program con- nected to its definition?
Answer :
 A reference to a non-locally variable in a static-scoped language with nested subprograms requires a two step access process:

1. Find the correct activation record instance

2. Determine the correct offset within that activation record instance


15. What is the general problem with static scoping?
Answer :
Usually too much access. Scope structure destroyed as program evolves.






- PROBLEM SET
1. Which of the following identifier forms is most readable? Support your decision.
SumOfSales
sum_of_sales
SUMOFSALES
Answer :
Sum Of Sales is the most readable. It is because it’s doesn’t have any problem with case sensitive, because the following identifier doesn’t use any caps lock.


2. Some programming languages are typeless. What are the obvious advan- tages and disadvantages of having no types in a language?
Answer :
- Advantages : allow users to write sloppy programs faster.
- Disadvantages : cannot control the data and variables, compiler cannot detect any mistakes.


3. Write a simple assignment statement with one arithmetic operator in some language you know. For each component of the statement, list the various bindings that are required to determine the semantics when the statement is executed. For each binding, indicate the binding time used for the language.
Answer :
(C++)
int count;count = count + 5;

Possible types for count: set at language design time. Type of count: bound at compile time.
Set of possible values of count: bound at compiler design time. Value of count: bound at execution time with this statement. Set of possible meanings for the operator symbol ““:*bound at language definition time.*Meaning of the operator symbol “” in this statement: bound at compile time.
Internal representation of the literal “5”: bound at compiler design time.


4. Dynamic type binding is closely related to implicit heap-dynamic vari- ables. Explain this relationship.
Answer :
 Implicit heap-dynamic variables acquire types only when assigned value, which must be at runtime. Therefore, this variable are always dynamically bound to types.


5. Describe a situation when a history-sensitive variable in a subprogram is useful.
Answer :
To describe a situation when a history-sensitive variable in a subprogram is useful, suppose that a FORTRAN subroutine is used to implement a data structure as an abstraction. In this situation, it is essential that the structure persists between different calls to the managing subroutine.







Kamis, 16 Oktober 2014

CHAPTER 4

Nama : Aditya Isnugraha
Class   : LM01
NIM    : 1801419606

Assignment from Tri Djoko Wahjono
CHAPTER 4

- REVIEW QUESTION
11. Describe the parsing problem for a bottom-up parser.
      Answer :


12. Explain why compilers use parsing algorithms that work on only a subset of all grammars.
      Answer :


13. Why are named constants used, rather than numbers, for token codes?
      Answer :
      - for the sake of readability of lexical and syntax analyzers.


14. Describe how a recursive-descent parsing subprogram is written for a rule with a single RHS.
      Answer :
     -A recursive-descent subprogram for a rule with a single RHS is relatively
      simple. For each terminal symbol in the RHS, that terminal symbol is compared
      with nextToken. If they do not match, it is a syntax error. If they match,
      the lexical analyzer is called to get the next input token. For each non terminal,
      the parsing subprogram for that nonterminal is called.


15. Explain the two grammar characteristics that prohibit them from being used as the basis for a      top-down parser.
      Answer : Two grammar characteristics that prohibit top-down parsing:
                      Direct or indirect Left Recursion.
   

- PROBLEM SET

 1. Perform the pairwise disjointness test for the following grammar rules.
a. A→aB b cBB
b. B→aB bA aBb
c. C→aaA b caB
Answer :
 (a) FIRST(aB) = {a}, FIRST(b) = {b}, FIRST(cBB) = {c}, Passes the test

(b) FIRST(aB) = {a}, FIRST(bA) = {b}, FIRST(aBb) = {a}, Fails the test

(c) FIRST(aaA) = {a}, FIRST(b) = {b}, FIRST(caB) = {c}, Passes the test


2. Perform the pairwise disjointness test for the following grammar rules.
a. S→aSb bAA
b. A→b{aB} a
c. B→aB a
Answer :
 a. FIRST(aSb)=a
    FIRST(bAA)=b
b. FIRST(b{aB}) = b
    FIRST (a) = a
c. FIRST(aB)=a
    FIRST(a) = a



3. Show a trace of the recursive descent parser given in Section 4.4.1 for the string a + b * c.
Answer :

a + b * c
Call lex /* returns a */
Enter <expr>
Enter <term>
Enter <factor>
Call lex /* returns + */
Exit <factor>
Exit <term>
Call lex /* returns b */
Enter <term>
Enter <factor>
Call lex /* returns * */
Exit <factor>
Call lex /* returns c */
Enter <factor>
Call lex /* returns end-of-input */
Exit <factor>
Exit <term>
Exit <expr>



4. Show a trace of the recursive descent parser given in Section 4.4.1 for the string a * (b + c).
Answer :
 call lex      // return a
            enter <expr>
            enter <term>
            enter <factor>
          call lex      // return *
            exit <factor>
          call lex      // return (
            enter <factor>
          call lex      // return b
            enter <expr>
            enter <term>
            enter <factor>
          call lex      // return +
            exit <factor>
            exit <term>
          call lex      // return c
            enter <term>
            enter <factor>
          call lex      // return )
            exit <factor>
            exit <term>
            exit <expr>
          call lex      // return EOF
            exit <factor>
            exit <term>
            exit <expr>



5. Given the following grammar and the right sentential form, draw a parse tree and show the phrases and simple phrases, as well as the handle. S→aAb bBA    A→ab aAB    B→aB b
a. aaAbb
b. bBab
c. aaAbBb
Answer :
 http://dominicvedericho.files.wordpress.com/2013/03/screen-shot-2013-03-27-at-6-20-39-pm.png
 http://dominicvedericho.files.wordpress.com/2013/03/screen-shot-2013-03-27-at-6-21-01-pm.png

















Kamis, 09 Oktober 2014

CHAPTER 3

Nama : Aditya Isnugraha
Class   : LM01
NIM    : 1801419606

Assignment from Tri Djoko Wahjono
CHAPTER 3

- REVIEW QUESTION

11. How is the order of evaluation of attributes determined for the trees of a
      given attribute grammar?
      Answer : Expr → Expr + Term
                     Expr → Term
                     Term → Term * Factor
                     Term → Factor
                     Factor → "(" Expr ")"
                     Factor → integer

12. What is the primary use of attribute grammars?
      Answer : An attribute grammar is an extension to a context-free grammar. The primary purpose                          of an attribute grammar is it allows certain language rules to be described, such as type                        of compatibility. An attribute grammar is a formal way to define attributes for the                                productions of a formal grammar, associating these attributes to values. The evaluation                        occurs in the nodes of the abstract syntax tree, when the language is processed by some                        parser or compiler.


13. Explain the primary uses of a methodology and notation for describing
      the semantics of programming languages.
      Answer : Object modeling techniques and notations presents a methodology using a completely                          different diagrams with other techniques commonly used for data modeling and process                      modeling.


14. Why can machine languages not be used to define statements in operational
      semantics?
      Answer : Machine language can not be used to define statements in operational semantics                                  because of some problems. First, the individual steps in the execution of machine
                     language and the resulting changes to the state of the machine are too small and too                              numerous. Second, the storage of a real computer is too large and complex.


15. Describe the two levels of uses of operational semantics.
      Answer : There are different levels of uses in operational semantics. At the highest level, the                               focus is on the final result of the execution of a program, this is sometime called natural                       operational semantics. At the lowest level, operational semantics can be used to                                   determine the precise meaning of a program through an examination of the complete                           sequence.




- PROBLEM SET



11. Consider the following grammar:
      <S> → <A> a <B> b
      <A> → <A> b | b
      <B> → a <B> | a
     Which of the following sentences are in the language generated by this
     grammar?
     a. baab
     b. bbbab
     c. bbaaaaa
     d. bbaab
     Answer : None of those are the language generated by the grammar, it should be k<A>aj<B>b,(A                     contains b and B contains a) in which the end will be a single b, the list of answer does                         not include an answer that ends with a single b


12. Consider the following grammar:
     <S> → a <S> c <B> | <A> | b
     <A> → c <A> | c
     <B> → d | <A>
     Which of the following sentences are in the language generated by this
     grammar?
     a. abcd
     b. acccbd
     c. acccbcc
     d. acd
     e. accc
     Answer : No one of the following statements are generated.


13. Write a grammar for the language consisting of strings that have n
      copies of the letter a followed by the same number of copies of the
      letter b, where n > 0. For example, the strings ab, aaaabbbb, and
      aaaaaaaabbbbbbbb are in the language but a, abb, ba, and aaabb are not.
      Answer : <S> => a<S>bb  | abb


14. Draw parse trees for the sentences aabb and aaaabbbb, as derived from
      the grammar of Problem 13.
      Answer :  We  first derive a grammar in order to know how to draw the tree.

                     <stmt> -> <A>

                    <A> -> a<A>b | ab

                    tree for aabb

                    tree for aaaabbbb


15. Convert the BNF of Example 3.1 to EBNF.
      Answer : <program> -> begin <stmt_list> end

            .       <stmt_list> -> stmt[stmt_list]

            .       <stmt> -> <var> = <expressions>

            .       <var> -> A| B | C