# concepts of programming language: chapter 16

Standard

Review Question
1. What are the three primary uses of symbolic logic in formal logic ?
– to express propositions, to express the relationships between propositions, and to
describe how new propositions can be inferred from other propositions that
are assumed to be true.

2. What are the two parts of a compound term ?
– functor and and ordered list of of parameters

3. What are the two modes in which a proposition can be stated ?
– one in which a proposition is defined to be true and one in which that the proposition is something to be determined.

4. What is general form of a proposition in clausal form ?
-B1 U B2 U . . . U Bn C A1 n A2 n . . . n Am

5. What are antecedents ? Consequents ?
– Antecedents are right side of a clausal form proposition. Consequent is left side of a clausal form propositions

6. Give general definitions of resolution and unification
– Resolution : inference rule that allows inferred propositions to be computed from given propositions, thus providing a method with potential application to automatic theorem proving.
Unification : Process of determining useful values for variables.

7. What are the forms of Horn clauses ?
– a. Have a single atomic proposition on the left side
b. empty left side.

9. What does it mean for a language to be nonprocedural ?
– Language in which the programs do not exactly state how a result is to be computed but rather describe the form of the result.

Problem Set
1. “All predicate calculus propositions can be algorithmically converted to clausal form”. Is this statement true or false ? Explain.
– True.

8. Critically comment on the following statement : “ Logic programs are nonprocedural”
– It is true, because logical programs use lots of different processes based on its conditions. If a certain logical requirement is true, then a program will execute the corresponding process, instead of procedurally executing the statements.

9. From a book on Prolog, learn and write a description of a monkey-banana prolem. Why does Prolog allow this problem to exist in its implementation ?
– The problem is defined as this : a monkey is in a room. Suspended from the ceiling is a bunch of bananas, beyond the monkey’s reach. However, in the room there are also a chair and a stick. The ceiling is just the right height so that a monkey standing on a chair could knock the bananas down with the stick. The monkey knows how to move around, carry other things around, reach for the bananas, and wave a stick in the air. What is the best sequence of actions for the monkey?
It exists to create a variation in output of Prolog. As Prolog is an AI programming language, a variation might be needed in AI output to make them respond relevant to the situation.

# concept of programming language: chapter 15

Standard

Review Questions
1. Define functional form, simple list, bound variable and referential transparency.
– Functional form : one that either takes one or more functions as parameters or yields a function as its result.
Simple list : A list that does not include sublist.
Bound variable : A bound variable is a variable which never changes in the expression after being bound to an actual parameter value at the time evaluation of the lambda expressions begin.
Referential transparency : A state where execution of function always produces the same result when given the same parameters.

2. What does a lambda expression specify ?
– parameters and the mapping of a function.

3. What data types were parts of the original LISP ?
– atoms and lists

4. In what common data structure are LISP lists normally stored ?
– As linked list structure in which each node has two pointers.

5. Explain why QUOTE is needed for a parameter that is a data list.
– To return lists or atoms without changing them.

6. What is a simple list ?
– A list that does not include a sublist.

7. What does the abbreviation REPL stand for ?

8. What are the three parameters to IF ?
– a predicate expression, a then expression, and else expression.

11. What are two forms of DEFINE ?
– Binds a name to value of an expression, and bind lambda expression to a name.

29. What is a curried function ?
– All functions that takes multiple parameters.

30. What does partial evaluation mean ?
– The function is evaluated with actual parameters for one or more of the leftmost formal parameters.

– A textual notation introduced by dispatch on one or two characters that defines special-purpose syntax

Problem Set
4. Refer to a book on Haskell programming and discuss the feature of Haskell.
– Haskell features lazy evaluation, pattern matching, list comprehension, type classes, and type polymorphism. It is a purely functional language, which means that in general, functions in Haskell do not have side effects. There is a distinct construct for representing side effects, orthogonal to the type of functions. A pure function may return a side effect which is subsequently executed, modeling the impure functions of other languages.
Haskell has a strong, static type system based on Hindley–Milner type inference. Haskell’s principal innovation in this area is to add type classes, which were originally conceived as a principled way to add overloading to the language, but have since found many more uses.
The construct which represents side effects is an example of a monad. Monads are a general framework which can model different kinds of computation, including error handling, nondeterminism, parsing, and software transactional memory. Monads are defined as ordinary datatypes, but Haskell provides some syntactic sugar for their use.

9. What does the following Scheme function do ?
(define (y s list)
(cond
((null? Lis) ‘ () )
((equal? S (car lis)) lis)
(else (y s (cdr lis)))
))
– y returns the given list with leading elements removed up to but not including the first occurrence of the first given parameter.

10. What does the following Scheme functions do ?
(define (x lis)
(cond
((null ? lis) 0)
((not (list? (car lis)))
(cond
((eq? (car lis) #) (x (cdr lis)))
(else (+ 1 (x (cdr lis))))))
(else (+ (x (car lis)) (x (cdr lis))))
– x returns the number of non-NIL atoms in the given list.

# concept of programming language: chapter 14

Standard

review question

1. Define exception, exception handler, raising an exception, disabling an exception, continuation, finalization, and built-in exception.

– Exception : any unusual event, erroneous or not, that is detectable by either hardware or software and that may require special processing.

Exception handler : a code unit which processes an exception.

Raising an exception : When a event associated with an exception occurs

Disabling an exception : Ignoring a certain hardware-detectable exceptions.

Continuation : Control transfer to somewhere in the program outside of the handler code or program might terminate .

Finalization : ability to complete some computation regardless of how subprogram execution terminates.

Built-in exception : Exception that is not made by the user, but rather comes as default.

2. When is an exception thrown or raised ?
– When an event associated with an exception occurs

3. What are the advantages of having support for exception handling built in to a language ?

– Without built-in exception handling, the code to detect error condition can be a clutter to the program. Existence of built-in exception handling would simplify a source program.

4. Give an example of hardware-detectable execution.

– Division by zero

5. What does it mean for an exception to be bound to an exception handler ?

– A specific exception is to be handled by a specific exception handler also, because different exceptions are to be treated differently.

6. What is exception propagation in Ada ?

– A powerful tool for constructing more reliable software systems.

8. Where does execution continue after an exception is handled in Ada ?

– Control simply continues after the exception clause.

10. What are the four exceptions defined in the Standard package of Ada ?

11. Are there any predefined exceptions in Ada ?

– Yes, there are, for example Ada.Text_IO defines the End_Error exception.

12. What is the use of Suppress pragma in Ada ?
– Run-time checks that are parts of built-in exceptions can be disabled in Ada programs

13. Describe three problems with Ada’s exception handling.

– The propagation model, which allows exceptions to be propagated to an outer scope in which the exception is not visible, inadequacy of exception handling for tasks, and exception handling was not extended to deal with new constructs in Ada 95.

Problem Set

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

– There were no possibility for the user program to detect or attempt to deal with errors. In case if error happens, the program will be terminated and control will be transferred to the operating system.

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

– C does not check subscript ranges. While in Java, compilers usually generate a code to check the correctness of every subscript expression. If any exception generates, 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, for example in Ada, using an error flag parameter in all subprograms. One advantage is that the code to test the error is eliminated after every call. Such test code makes program longer and harder to read. Second advantage is that exceptions can be propagated farther in a uniform and implicit way. Also, there is an advantage that all program use a similar method to deal with exceptions, which enhances readability.

7. In a language without exception-handling facilities, we could send an error-handling procedure as a parameter to each procedure that can detect errors that must be handled. What disadvantages 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.

# concept of programming language: chapter 13

Standard

Review Questions
1. What are the three possible levels of concurrency in programs ?
– Instruction level, Statement level, and Unit level

2. Describe the logical architecture of an SIMD computer.
– In an SIMD computer, each processor has its own local memory. One processor controls the operation of the other processors. Because all of the processors, except the controller, execute the same instruction at the same time, no synchronization is required in the software.

3. Describe the logical architecture of an MIMD computer.
-Each processor in an MIMD computer executes its own instruction stream. MIMD computers can appear in two distinct configurations: distributed and shared memory systems. The distributed MIMD machines, in which each processor has its own memory, can be either built in a single chassis or distributed, perhaps over a large area. The shared-memory MIMD machines obviously must provide some means of synchronization to
prevent memory access clashes.

4. What level of program concurrency is best supported by SIMD computers ?
-Instruction concurrency level

5. What level of program concurrency is best supported by MIMD computers ?
-Unit concurrency level.

6. Describe the logical architecture of a vector processor.
– Vector processor have groups of registers that store the operands of a vector operation in which
the same instruction is executed on the whole group of operands simultaneously.

7. What is the difference between physical and logical concurrency ?
– Physical concurrency is when it is assumed that if more than one processor is available, several program units from the same program literally execute simultaneously. Logical concurrency is assuming multiple processors can execute simultaneously while the actual execution is taking place in a single processor.

8. What is the work of a scheduler ?
– Managing the share of processors among tasks.

9. Give some examples of languages which can be used for synchronization.
– Ada 95, Java, C#, F#, Python and Ruby

10. When is a task in a blocked state ?
– When its execution is interrupted by one of several different events

11. Give three characteristics of thread that distinguish them from subprograms
– A task may be implicitly started, whereas a subprogram must be explicitly called.
– When a program unit invokes a task, in some cases it need not wait for the task to complete execution before continuing its own.
– When execution of task is completed, control may or may not return to the unit that started that execution

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

13. Define task ,synchronization, competition and cooperation synchronization, liveness ,race condition and deadlock.
– Task : unit of a program, similar to a subprogram that can be in concurrent execution with other units of same program
Synchronization : a mechanism that controls the order in which task execute.
Competition Synchronization : Synchronization between two task when both require a single resource that can’t be used together.
Cooperation Synchronization : Synchronization in which a task must wait for other task to finish before it can begin or continue its execution
Liveness : condition if some event, like program completion is supposed to occur, it will occur eventually. That is, progress is actually made.
Race Condition : When two or more tasks are racing to use the shared resource and the behavior of the program depends on which task arrives first.
Deadlock : a condition when a program is trapped inside an endless loop due to error between task synchronization.

14. What kind of tasks do not require any kind of synchronization ?
-Tasks that are not depending on the outcome or output from other tasks.

15. Describe the five different states a task can be.
– New = A task is in the new state when it has been created but yet to start its execution
– Ready = A task that is ready to run but is not currently running. Either it has not been run yet or it had run previously but got blocked.
– Running = A task that is currently being executed.
– Blocked = a task that has been running ,but the execution was interrupted by an event.
– Dead = A task that is no longer active in any sense, either when the execution is completed or killed by the program

16. What is task descriptor ?
– A data structure that stores all of the relevant information about the execution state of a task.

17. In the context of language support for concurrency, what is a guard ?
– Linguistic device that allows the guarded code to be executed only when a specified condition is true.

Problem Set.

1. Explain clearly why a race condition can create problems for a system .
– A race condition allows different outputs to come out of the synchronization, as stated in the book, for example task A which increments an integer and task B that multiplies an integer with 2.
Say we have integer A with value of 3. If both tasks are run in race condition, its value could be either 7 (when B runs and finishes before A starts) or 8 (vice versa) or, either 4 or 6 (if they started at the same time, 4 when A finishes later and 6 when B finishes the last. ). Without proper synchronization on timing, the output can vary. Thus this makes the program unreliable.

2. What are the different ways to handle deadlock ?
– One of the ways is to design algorithm where tasks that can cause deadlock to not to run together. Or, to allow them to execute at the same time but with an exception if a deadlock happens, the program will either reset its status to the time when deadlock has not occurred or to break forcefully from the loop and continues execution.

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 ?
– A continuous check might mean a deadlock for a task, where it does something that does not has a direct impact on the program unless the specified event happens. It does consume extra processor capability. A better way to do this might be executing the same task when an event occurs, instead of running it first and make it waiting and continuously wasting CPU capability.

# concept of programming language: chapter 12

Standard

REVIEW QUESTION:

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.

8. What is an abstract method ? What is an abstract class ?
– a method which all descendant classes should have. An abstract class is a class which has abstract method.

10. What is an inner class ?
– Non-static classes that are nested directly in another class

11. What is the message protocol of an object ?
– Colletions of an object’s methods.

12. From where are Smalltalk objects allocated ?
– From the heap

38. What is Boxing ?
– Coercion of primitive values when they are put in object context

52. Does Ruby support multiple inheritance ?
– No. it does not

Problem Set

2. In what ways can “compatible “ be defined for the relationship between an overridden method and the overriding method ?
– in ways of its formal definition, the parameters and return types.

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.

– In Java, there’s no access level specifier of inheritance, while C++ has private public and protected.

– In Java, the functions are virtual by default. While in C++ the functions CAN BE MADE virtual with the keyword virtual

7. What is one programming situation where multiple inheritance has a significant disadvantage over interfaces ?
– When two or more parent classes are derived from one grandparent class and has one child. (diamond problem)

9. Given an example of inheritance in C++, where a subclass overrides the superclass methods.
– class human{
public :
void eat(){std::cout<<”Eating”;}
}
class man : public human{
public :
void eat(){std::cout<<”Eat like a boss”;}
}

10. Explain one advantage of inheritance
– Allows programmer to reuse a class with modifications that doesn’t apply to the initial class, so both class can still be used. This also improves readability and writability.

14. Explain type checking in Java
-Type checking happens before execution. Type checking can only uses type information that have declared in your program, and not the possible type that an object has at runtime. Java checks all line of code to make sure that it uses values correctly according to the declared types.

16. State why Java is said to be more pure object oriented than C++.
-Because Java implements pure class. Every function / statements in Java is run by a class. While in C++ not all functions are run by a class.

17. What are the different options for object destruction in Java ?
– Using Close method or Finalize method.

# concept of programming language: chapter 11

Standard

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.

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

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 ?

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

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.

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

# concept of programming language: chapter 10

Standard

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)

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

3. What must be stored for the linkage to a subprogram ?

– Execution status information

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

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.

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?

There are two options for implementing blocks as parameterless subprograms: One way is to use the same activation record as a subprogram that has no parameters. This is the most simple way, because accesses to block variables will be exactly like accesses to local variables. Of course, the space for the static and dynamic links and the return address will be wasted. The alternative is to leave out the static and dynamic links and the return address, which saves space but makes accesses to block variables different from subprogram locals.

# concept of programming language: chapter 9

Standard

REVIEW QUESTION:

1.    What are the three general characteristics of subprograms?

• Each subprogram has a single entry point, excluding co-routine.
• The calling program 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.

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

# concept of programming language: chapter 8

Standard

Review Questions
1. What is the definition of control structure ?
Control structure is a control statement and the collection of statements whose execution it controls.

2. What did Bohm and Jocopini prove about flowcharts?

It was proven that all algorithms that can be expressed by flowcharts can be coded in a programming languages 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 ?

7. Under what circumstances must an F# selector have an else clause?

An F# selector have an “else” clause if  the “if” expression does return a value.

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

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.

# concept of programming language: chapter 7

Standard

Review Questions
1. Define operator precedence and operator associativity.
Operator precedence is a rule used to clarify which procedures should be performed first in a given mathematical expression.
Operator associativity is a property that determines how operators of the same precedence are grouped in the absence of parentheses

2.    What is a ternary operator?
A ternary operator is an operator with three operands.
3. What is a prefix operator ?
An operator which signifies function of one argument which argument immediately follows an occurrence of the operator
4. What operator usually has right associativity ?
The “=” operator
8. Define functional side effect
A condition where a function changes either one of its parameters or a global variable.
9. What is a coercion ?
A method of automatically converting one type of data to another.
10. What is a conditional expression?
Conditional expression is a statement that uses if-then-else statements.

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

12. Define narrowing and widening conversion
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.

15. What is referential transparency?
Referential transparency is 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 .
1. When might you want the compiler to ignore type differences in an expression ?
When I want to evaluate a string as a number vice versa.

2. State your own arguments for and against allowing mixed-mode arithmetic expressions.
FOR :
A mixed mode arithmetic expression is needed in calculating expressions that might have decimal results. It is compulsory as it allows two different type of number data type such as float and integer to be summed without losing the precision of the float.
Against :
While it is compulsory to have mixed-mode expressions, it is more error prone when expressions made are more likely to have non-decimal results. A mixed mode might produce a decimal result even though the result wanted is a non-decimal.

3. Do you think the elimination of overloaded operators in your favorite language would be beneficial ? why or why not ?
No, it would not be beneficial. Overloading operator would be a helpful feature in developing a complex program with complex arithmetic operation as well. It allows developers to create a class whose function can replace countless lines of codes with an operator. This clearly will help a readability and writability of a program. Eliminating overloaded operators would null this advantage.

4. Would it be a good idea to eliminate all operator precedence rules and require parentheses to show the desired precedence in expressions ? Why and why not ?
No , it would not be a good idea. Although this custom precedence sounds like increasing flexibility, requiring parentheses to show a custom precedence would impact in readability and writability of a program.

5.    Should C’s assigning operations (for example, +=) be included in other languages (that do not already have them)? Why or why not?
Yes, because we can make the operator simpler than before. We can just write a+=b instead a=a+b.