3 Pages

Lecture02

Course: CS 2130, Fall 2009
School: East Los Angeles College
Rating:
 
 
 
 
 

Word Count: 6803

Document Preview

Programming CS2130 Language Concepts and Paradigms Lecture 2 -- Programming Language Concepts Every programming language has syntax and semantics: The syntax of a programming language is concerned with the form of expressions, commands and declarations etc. and with how these are put together to form a program. The semantics of a programming language is concerned with the meaning of programs, that is how they...

Register Now

Unformatted Document Excerpt

Coursehero >> California >> East Los Angeles College >> CS 2130

Course Hero has millions of student submitted documents similar to the one
below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.

Course Hero has millions of student submitted documents similar to the one below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.
Programming CS2130 Language Concepts and Paradigms Lecture 2 -- Programming Language Concepts Every programming language has syntax and semantics: The syntax of a programming language is concerned with the form of expressions, commands and declarations etc. and with how these are put together to form a program. The semantics of a programming language is concerned with the meaning of programs, that is how they behave when executed. A program may be syntactical correct, that is each component command and declaration may be of the correct form and these may be ordered correctly, and yet be invalid semantically. For example a procedure may be called with the wrong number or wrong type of parameters, the operands in an expression may be of different types when they are required to be of the same type or the programmer may have referenced a non-existent field in a record. In this course we will be mainly concerned with semantic issues. A given construct may be provided in several languages with differences in syntax which are merely superficial. For example the following while loops are essentially equivalent: Ada WHILE condition LOOP commands to be repeated END LOOP; Java, C and C++ while (condition) { commands to be repeated } Semantic features are more important. We need to appreciate subtle differences between apparently similar constructs such as the CASE statement in Ada and the switch statement in C and Java. As an example of semantic differences consider the following: given that the first pair of declarations are essentially equivalent we might be misled into thinking that the second pair are also equivalent. However in the Java/C version only the variable B is initialised: Ada A, B : Integer; A, B : Integer := 1; Java, C and C++ int A, B; int A, B = 1; // initialises B only // should be int A = 1, B = 1; // to initialise both variables As a matter of style to avoid any possible confusion, it would be better to write the initialising declarations on separate lines A : Integer := 1; B : Integer := 1; int A = 1; int B = 1; We will consider those semantic concepts that are so important they are supported (or ought to be supported) in any good programming language and consider how well a given language supports particular concepts and whether it confuses distinct concepts. Names A name is a string of characters used to identify some entity in a program (such as a variable, type, subprogram etc.) Names are often referred to as identifiers. A number of issues arise: What is the maximum length of a name? Are names case sensitive? Can connector symbols such as underscore be used in names? Do some character strings have a special meaning as reserved words or keywords of the language? Early programming languages allowed only single character names, other languages place limits on maximum name length (6 in FORTRAN 77, 31 in C and FORTRAN 90) while in others for example Java and Ada there is no limit. A design consideration is that the limit on name length A Barnes, 2005 1 CS2130/Lect 2 (if any) should be sufficiently large so that in practice the programmer's choice of meaningful names is not restricted. In some languages, notably C, C++ and Java, names are case sensitive, thus count, Count and COUNT all count as different names whereas others (notably Ada) are not case sensitive. There is no universal agreement as to which system is preferable. Certainly use of names differing only in the case of one or two letters reduces program readability (by other programmers) and may lead to obscure bugs if the programmer mistypes a name. Whether a language is case sensitive or not, a judicious use of case in long names can improve program readability, for example TotalSoFar is generally regarded as preferable to totalsofar. The precise rules for valid names differ from language to language but generally names consist of letters and digits and must start with a letter (so that it is easy to distinguish between names and number literals). Often underscores are allowed in names; they can be useful in improving the readability of multi-word names, for example total_so_far is generally regarded as preferable to totalsofar. The counter argument is that an underscore looks too much like an operator and so if overused can reduce program readability. Also it is often mistyped as a minus sign, which can lead to obscure bugs if the component words in a name are also valid names of program variables. Some languages notably Ada only permit underscore as a separator of other characters in a name (thus a name may not start or end with an underscore nor contain consecutive underscores). Other languages allow names to begin or end with an underscore, generally as a matter of style such names should be avoided as there is no argument regarding readability here. In some languages other symbols such as $ are allowed in names, often they denote that the name has some special 'system' meaning (e.g. string variables in Basic). In almost all languages there are special words such as while, if etc. that have a special meaning in the language and mark the various parts of program control structures. Such a word is referred to as a reserved word if it cannot be used as the name of a normal program entity whereas it is referred to as a keyword if it has a special meaning only in certain contexts and can be used as a name in other contexts. It is now fairly generally accepted that reserved words are preferable as a design choice compared with keywords as the latter can lead to readability problems. For example in FORTRAN one could write declarations such as INTEGER REAL REAL INTEGER The first defines a variable with the name REAL to be of type INTEGER (a keyword in FORTRAN) whilst the second defines a variable with the name INTEGER to be of type REAL (also a keyword); all very confusing. In some languages certain names though not reserved or keywords are always defined in the standard language environment (for example the types Integer, Character and Boolean in Ada). Although they may be redefined by the programmer, such practices are best avoided as they normally lead to severe readability problems. Other names such as the names of procedures and functions in standard libraries are also predefined. Examples are the subprogram names such as Put and Get in the Ada package Ada.Text_IO and the functions in the Standard C I/O library such as fgetc, fputc, printf, and scanf etc. These are available in any program that 'imports' the standard libraries. In case-sensitive languages predefined, reserved or keywords must, of course, be spelt with the correct case (lower case in C, C++ and Java). Even in languages which are not case-sensitive, programmers often adopt case conventions for typing reserved or predefined names as these are thought to improve program readability. A common but by no means universal convention is that keywords are typed in upper-case. Exercise Find out (by consulting a suitable Java textbook or on-line manual) whether type names such int , byte , char etc. are reserved words, keywords or predefined names in Java (and in C/C++). A Barnes, 2005 2 CS2130/Lect 2 Commands and Expressions An expression is anything that can be evaluated to produce a value. An expression may be contain sub-expressions which may be split up into further sub-expressions. Parentheses often show the division of an expression into sub-expressions where this is not uniquely specified by operator precedence. Literals The simplest expressions are literals which directly denote values of some type: 3.14159 0 'A' "The answer is " Jan As in the last example an enumerated type value denotes a value directly and so is a literal. Variables The next simplest form of expression is a variable name); the value of the expression is the current value of that variable. Function and Operator Calls A function call applies a function to its arguments yielding a result. An operator call is, in principle, no different from a function call. Infix operators such as +, , *, / etc. are simply more readable designations of certain functions, for example in Ada: "+"(3, 4) is equivalent to 3 + 4 Operators may be applied to literals, variables and other expressions to build up complex expressions. Most operators are either binary infix (such as +, , *, /, >, <, =, AND, OR etc.) with the operator symbol written in between the two operands or unary prefix (such as +, , NOT, etc.) with the operator preceding the single operand. Note that (in some languages such as Ada) there are no literals for negative numbers rather terms such as 2 or 3.1 are expressions made up of the unary prefix operator applied to the literals 2 and 3.1 respectively. Occasionally languages permit unary postfix operators and/or ternary operators. For example in C, C++ and Java the auto-increment and auto-decrement operators can be used a unary prefix or postfix operators. ++a a++ prefix (value is value of a after increment) postfix (value is value of a before increment) The conditional operator "? :" in C, C++ and Java is ternary; for example tax = (income > threshold)? (income - threshold)* taxrate : 0; This sets tax to zero if income is less than or equal to the threshold , otherwise it sets it to 23% of the income in excess of the threshold (assuming taxrate==0.23). Precedence of Operators Where two or more binary operators occur in an expression there is a potential ambiguity unless parentheses are used to specify which operators should be applied first. For example is 4*5+3 interpreted as (4*5)+3 = 23 or as 4 *(5+3) = 60 and is 1032 interpreted as (103)2 = 5 or as 10(32) = 9? To resolves such ambiguities operators are assigned a precedence level and (in the absence of brackets) an operator with a higher precedence is applied before one with a lower precedence. In most (all?) languages the multiplicative operators (* and /) have a higher precedence than additive ones (+ and ). Thus 4*5+3 is interpreted as (4*5)+3 = 23. Where two operators are of equal precedence it is usual to evaluate the leftmost one first (left associativity). Thus 1032 is interpreted as (103)2 = 5. However left associativity is by no means universal. When using the exponentiation operator in Ada we must explicitly specify the order of evaluation by using brackets; for example A**B**C is illegal we must write either A**(B**C) or (A**B)**C to explicitly specify which of the two (different) meanings is intended. Also we will see below example of operators which associate to the right (for example the assignment operators =, += etc. in C and Java). Generally comparison operators and Boolean operators have a lower precedence than arithmetic ones and usually comparison operators have a higher precedence than Boolean ones. Thus for A Barnes, 2005 3 CS2130/Lect 2 example we can write X>Y AND Z>0 without brackets in Ada and similarly x>y && z>0 in C and Java. However in Modula-2 comparison operators have a lower precedence than Boolean ones so that it is necessary to write (X>Y) AND (Z>0). In most languages logical AND has a higher precedence than OR. Thus in C and Java the expression a || b && c is interpreted as a || (b && c) and brackets must be used if || is to be evaluated first, i.e. (a || b) && c. Ada is somewhat of an exception as AND and OR have the same precedence and brackets must be used to make the order of evaluation clear. Thus A OR B AND C would cause an compilation error; one must write either A OR (B AND C) or (A OR B) AND C to explicitly specify which of the two (different) meanings is intended. When translating complex expressions involving many operators from one language to another one needs to be aware that the precedence rules may differ from one language to the next and so the meaning of an expression may be different in the two languages; consult the precedence rules for the languages concerned to see whether it is necessary to add extra parentheses to preserve the meaning of an expression when translating code from one language to another. When writing new code involving complex expressions, it is a good idea to use extra brackets to make the intended order of evaluation explicit rather than relying on (perhaps obscure) precedence rules of the particular language. This avoids 'nasty surprises' and makes code easier to read and maintain. Of course the insertion of redundant bracket pairs should not be overdone as this too reduces readability of the code. Defining New Operators Some languages for example Ada and C++ allow new overloadings of existing operator symbols to be defined. For example in Ada: TYPE Vector is ARRAY(Positive RANGE <>) OF Float; Different_Size : EXCEPTION; FUNCTION "+"(Left, Right : Vector) RETURN Vector IS -- normal vector addition Result : Vector(Left'Range); BEGIN IF Left'First = Right'First AND Left'Last = Right'Last THEN FOR I IN Left'Range LOOP Result(I) := Left(I) + Right(I); END LOOP; ELSE RAISE Different_Size; END IF; RETURN Result; END "+"; FUNCTION "*"(Left : Float; Right : Vector) RETURN Vector IS -- scalar multiplication Result : Vector(Right'Range); BEGIN FOR I IN Right'Range LOOP Result(I) := Left * Right(I); END LOOP; RETURN Result; END "*"; Then given suitable declarations A, B, C, D, E : Vector(1 .. 3); X : Float; we can write C := A + B; D := X*C; E := A*2.0; -- !? illegal as "*" above only permits Float*Vector A Barnes, 2005 4 CS2130/Lect 2 Exercise Define a second new overloading of "*" to allow expressions such as A*2.0 where A is of type Vector, to be written legally. In Ada and C++ only existing operators can be given new overloadings; the number of operands and the precedence level of the operator cannot be changed. In some languages such as PL1 (and some languages for algebraic computing such as Reduce) it is possible to define new operators and to set their precedence level. However, as this feature considerably complicates the parsing of the language by the compiler or interpreter, such extensions are not normally available in main stream imperative languages. Aggregates An aggregate yields a value of a composite type and can be regarded as literals for composite types. for example in Ada, we have: (1, 2, 3, 4) (1 .. 10 => 0.0) positional and named array aggregates ("Alan", (7, 7, 1947)) positional record aggregate (Name => "Alan", DOB => (Day => 7, Mth => 7, Yr => 1947)) named record aggregate Aggregates can be used to initialize composite data structures such as arrays and records (structures in C). Ada permits both named and positional association in array and record aggregates whereas most languages allow only positional association. In Ada the component values may be any expression of the appropriate type. Other languages have more restrictive rules; for example in Pascal the values in aggregates must be literals. In C and C++ the values must also be literals and furthermore aggregates may only be used to initialise arrays and structures (records) when they are declared; they may not be used to assign values in normal assignments. Commands The state of a computation at a particular time comprises an internal state which includes the current values of all extant1 variables and an indication the next instruction2 to be executed and an external state which includes the state of all its input and output streams. Imperative languages support explicit modification of the program state by the execution of commands. Commands include assignment, input and output operations3, selections (IF and CASE etc.), repetitions (WHILE, FOR etc.) and procedure call steps. Modification of program state may be direct via assignment to program variables or execution of I/O commands or indirect through control constructs and procedure calls which control other commands. Some languages notably functional languages (such as Haskell and Miranda) are based entirely on function evaluation and have no constructs that modify program state, that is they have no commands. Instead computation is organised by combining functions through functional composition (function of a function) and by higher order functions which can (for example) apply a function to an arbitrary list. Compound Commands Although only IF and WHILE compound commands together with sequencing are sufficient to express any algorithm, most languages provide additional selection and repetition commands for increased convenience and enhance clarity when expressing certain common constructs (FOR for loops controlled by a count, CASE for multi-way selections based on a single value). One major issue is how the end of the commands comprising the body of the compound command is determined. There are three approaches commonly used in the major programming languages. The body of a compound command is syntactically a single command. If the body is to contain more than one command then these commands must enclosed in a block or grouping construct. 1 2 extant = existing (more or less) or in parallel programs with multiple threads of execution the next instruction to be executed in each thread. 3 In some languages such as Pascal I/O operations are built-in whereas in others C, C++, Ada, and Java I/O is provided by the provision of 'standard' library procedures. A Barnes, 2005 5 CS2130/Lect 2 The end of the body of a compound command is marked by a special keyword typically END The extent of the body of a compound command is marked by indenting the body relative to reserved or key word(s) defining the command. The first approach is exemplified by C, C++, Java, Pascal and RLisp. Thus we have C, C++, Java if (condition) command; else command; while (condition) command; If necessary in C, C++ or Java multiple commands can be grouped as a single command by enclosing them in a block {...}. if (condition) { commands } else { commands } while (condition) { commands } In Pascal commands are grouped by enclosing them between BEGIN ... END;. In RLisp commands can be grouped by enclosing in a group statement <<...>>. Ada, Algol and Modula-2 exemplify the second approach. The parts of a compound command are delimited by keywords such as THEN, ELSE and END and multiple commands can be inserted between these keywords. Ada IF condition THEN commands; ELSE commands; END IF; WHILE condition LOOP commands; END LOOP; Some languages (e.g. Algol) use keywords spelt backwards fi, esac etc. to terminate the compound command whereas others notably Ada use END followed by a keyword identifying the type of compound command (END IF, END LOOP, END CASE etc.). Modula-2 on the other hand marks the end of all compound commands with a simple END. The first two approaches are superior as they allow better error detection/diagnostics, for example in Modula-2 and Ada Modula-2 MODULE P; variable declarations BEGIN WHILE condition DO commands IF condition THEN commands commands END commands END. Ada PROCEDURE P IS variable declarations BEGIN WHILE condition LOOP commands IF condition THEN commands commands END LOOP; commands END P; Here the user has accidentally omitted the END keyword for the IF statement; the Modula-2 compiler cannot detect an error until the end of the module is reached as it interprets the END that is intended to terminate the WHILE as the end of the IF whereas in Ada the error is detected at the END LOOP line as END IF is expected. Note similar problems arise with providing good diagnostics in the C family of languages if a closing brace } is accidentally omitted. The third approach is exemplified by the scripting language Python (and also the parallel processing language Occam) where indentation delimits the extent of compound commands. In such a language correct indentation is obviously essential and it is important to use a fixed width font when printing a program in such a language so that indentation is correctly displayed. A Barnes, 2005 6 CS2130/Lect 2 x = 10 while x > 0: if x == 3: print 'ignition', else: print x, x = x-1 print 'lift-off', # last line of if # last line of while Of course it is good programming style in any language to emphasize the logical structure by use of indentation as this improves program readability and aids debugging by providing visual cues to the human reader. The Dangling else The first approach has a pitfall for the unwary; consider the following Java code which is intended to output either the message "Positive" or "Negative" depending on the sign of the variable x (whereas if x is zero no message should be output): if (x >= 0) if (x > 0) System.out.println("Positive"); System.out.println("Negative"); In else fact the message "Negative" is output only when x is zero and nothing is output when x is negative. The problem is that in the C family of languages the syntax is potentially ambiguous: it is not clear whether the else part should belong to the first or second if command. The ambiguity is resolved in C, C+= and Java by (rather arbitrarily) decreeing that the else part belongs to the nearest if command. Hence the indentation that reflects the actual meaning should be if (x >= 0) if (x > 0) System.out.println("Positive"); else System.out.println("Negative"); Note that the ambiguity is nothing to do with the fact we have omitted curly brackets around the alternative commands in the selection, the following fragment has exactly the same meaning as the one above: if (x >= 0) if (x > 0) { System.out.println("Positive"); } else { System.out.println("Negative"); } To get the meaning implied by the indentation we must enclose the nested if in an extra block (the closing brace then serves to terminate the inner if): if (x >= 0) { if (x > 0) System.out.println("Positive"); } else { System.out.println("Negative"); The problem of the 'dangling else' also occurs in C, C++ and Pascal and indeed any language adopting the first approach to delimiting the extent of compound commands. It cannot occur in languages which, such as Ada, have an explicit keyword to terminate compound commands nor in languages such as Python where indentation is significant and servers to indicate the extent of compound steps. A Barnes, 2005 7 CS2130/Lect 2 Multi-way selections A simple IF command allows for two-way selections and one way selections (depending on whether there is an ELSE part or not). Some languages, such as Ada, allow a single IF command to be used for multi-way selections by allowing zero or more ELSIF (or in some languages elif) parts; the IF command is terminated by a single END. Other languages only permit such multi-way selections by using nesting IF's (with the need to terminate each IF with a corresponding END IF should the language require it or with the danger of potential ambiguity if there is no explicit terminator as in C and Java). Note also the Lisp COND command is equivalent to an IF with (optional) ELSIF and ELSE parts: (COND ((condition1 commands1) (condition2 commands2) (condition3 commands3) ........ (T commandsN)) ) CASE or switch IF condition1 THEN commands1 ELSIF condition2 THEN commands2 ELSIF condition3 THEN commands3 ........ ELSE commandsN END IF; Most languages provide a construct for multi-way selections based on the value of a single expression. C, C++ switch (month) { case dec: case jan: season = winter; case mar: case apr: season = spring; ............ } case feb: break; case may: break; Ada CASE Month IS WHEN Dec|Jan|Feb => Season := Winter; WHEN Mar .. May => Season := Spring; .......... END CASE; where month and season are of two suitable enumeration types. Several issues arise: What types are allowed for the governing expression? Does control fall through from one alternative to the next unless explicitly prevented? Can a default action be provided? Must the governing expression match one of the alternatives (if a default is not provided)? Generally most languages restrict the type of the governing expression to be discrete (of an integer, character or enumeration type). However a few scripting languages permit more general types (strings, real values etc.) in a similar fashion to allowing more general types to be used as array subscripts. Generally an explicit alternative can only appear once in the case or switch command; to allow an alternative to appear more than once would result in non-deterministic program behaviour. In some languages, notably C, C++ and Java, control falls through from one case clause to the next unless the switch command is explicitly exited with a break command. Although this can be a useful trick occasionally, it can lead to maintenance problems if a later programmer inserts extra alternatives in the switch statement between the original two alternatives. For this reason and on the grounds of frequency, in most modern languages (including Ada) at most one case alternative is executed and control then passes to the end of the CASE. We note in passing that Ada provides an number of ways of specifying the alternatives namely single alternatives, several alternatives separated by "|" or a range of alternatives specified with "..". In the C family of languages only single alternatives are allowed although the effect of a list of alternatives can be achieved by supplying no code corresponding to some alternatives and falling through to the next case (as in the example above); this is probably the only case where use of 'fall-through' can be recommended. Most languages allow a default (catch-all) part of a case or switch statement which is executed if the value of the governing expression does not match any of the supplied alternatives. For obvious reasons this must be placed after all explicit alternatives and so use of break is superfluous in this case). A Barnes, 2005 8 CS2130/Lect 2 C, C++, Java default: commands Ada WHEN OTHERS => commands In Ada all possible values of the governing expression must appear explicitly in the list of alternatives or there must be a catch-all WHEN OTHERS => alternative otherwise a compilation error occurs. In many other languages (including C and Java) if a particular alternative does not appear and if there is no default alternative then control simply passes to the end of a case or switch command. Repetitions Virtually all imperative languages provide a pre-conditioned while loop for indefinite repetitions. The commands in the loop body are repeated until the controlling condition becomes false and if the controlling condition is initially false the loop commands are not executed at all. Some languages also provide a post-conditioned loop in which the controlling condition is evaluated at the end of the loop so that the loop body is always executed at least once. C, C++, Java do { commands while (condition); Pascal REPEAT commands UNTIL condition; Note that in the former case the loop continues whilst the controlling condition is true, but in the latter it continues until controlling condition is true. Pre-determined Repetitions Most imperative languages provide a for loop to control iterations where the number of repetitions is known in advance. Several issues arise: What types are allowed for the controlling loop variable? Is the loop variable local to the loop or is it declared normally and so obeys normal scope rules? If the latter what is its final value? Can the loop variable be altered explicitly? Is the final bound for the loop variable evaluated once before the loop starts or before each loop iteration? Are reverse loops supported and are increments/decrements other than unity supported? Generally real values are not recommended in for loops even if the language permits it (as in C and Java) due to the problem of rounding errors; the loop might be executed one more time or one fewer time than expected; for example for (float x = 0.0; x <= 10.0; x += 1.0/3.0) { commands } As 1/3 cannot be represented exactly in binary or denary, the loop might only be executed 30 times rather than the expected 31 times. Similarly if <= were replaced by < the loop might be executed 31 times rather than the expected 30 times. In Ada the loop variable can be of any discrete type (integer type, modular type, character type or an enumeration type) whereas in some languages only integer types are allowed. In Ada, the loop variable is declared implicitly by the FOR command and its type is deduced from the type of the supplied limit values. In Ada the loop variable cannot be altered explicitly in the loop body and its scope is local to the loop body. In some languages (including the C family) a more permissive approach is adopted. The loop variable may be declared in the normal way and obeys normal scope rules. The loop variable can also be altered explicitly in the loop body. Although this is undoubtedly very flexible it means that the FOR loop becomes an indefinite loop; the number of repetitions is not fixed in advance. In some languages (e.g. Ada) the final loop bound is evaluated only once before the first iteration of the loop whereas in others (C family and Basic) it is evaluated before each loop A Barnes, 2005 9 CS2130/Lect 2 iteration. The former has the advantage that the number of iterations is fixed before the loop starts whereas in the latter case the loop again becomes indeterminate. Ada N := 100; -- loop executed 100 times FOR I IN 1 .. N LOOP Put(I); New_Line; N : = N - 1; END LOOP; C n = 100; /* loop executed 51 times */ for(i = 1; i <= n; i++) { printf("%d\n", i); n--; } In some languages (Basic, C family, Pascal and Modula-2) the loop variable can be incremented by any integer amount; negative increments giving rise to reverse loops. Ada is more restrictive; (in effect) the only permitted step sizes are 1 even though (constant) step sizes do not make the loop indeterminate. Some languages (some Lisp dialects and some scripting languages) permit iteration over lists as well as integer ranges. For example in RLisp: L := {1, 3, 9, 12, 25}; FOREACH elem IN L DO WRITE elem^2; # outputs 1, 9, 81, 144, 625 As we have indicated above in C, Java and related languages the for loop is really a generalised while loop with automatic initialisation and update of the loop variable(s). In Java the for loop for (initialisation steps; condition; update steps) { commands } is equivalent to { initialisation steps while (condition) { commands update steps } } Since there is (essentially) no restriction on the initialisation and update steps, it can be used for programming very complex loops controlled by several loop variables as well as simple 'counting' loops. Note the outer pair of braces {} which means that in Java the scope of any variable defined in the initialization steps is restricted to the for command. However, in C + + the for command is equivalent to the code above without the outer enclosing braces so a loop variable declared in a C++ for command extends beyond the end of the for command to the end of the block in which the for command occurs. It might be thought that the following Java and Ada loops would be equivalent for(byte b = 0; b <= 127; b++) { System.out.println(b); } FOR B IN 0 .. 127 LOOP Ada.Integer_Text_IO.Put(B); New_Line; END LOOP; However there is a trap for the unwary in the Java code! In Java arithmetic wraps around so adding one to the bytet value 127 produces 128 and thus the loop is infinite. To avoid this problem b would need to be declared as short (or int) though the problem would reappear if we wanted a for loop to iterate up to and including the largest allowed short (or int) value. The Ada for loop is more structured (and therefore less error-prone), but is undoubtedly less flexible as it can only be used for simple 'counting' loops. More on Repetitions Ada provides a general LOOP which continues until an explicit EXIT command is encountered. This permits loops where the controlling condition can be placed anywhere in the loop or indeed there can be multiple exits from the loop with distinct controlling conditions. A Barnes, 2005 10 CS2130/Lect 2 LOOP EXIT WHEN End_Of_File; Get(Ch); Count := Count + 1; EXIT WHEN Ch = 'Q' OR Ch = 'q'; process this character END LOOP; The general Ada loop thus allows post-conditioned loops to be programmed. Note that EXIT can also be used in other Ada loops (WHILE and FOR). If the loop occurs in a subprogram, a RETURN terminates the loop and causes the subprogram to return control to its caller. In the C family of languages there is no general loop command but the same effect can be achieved by using a loop whose controlling condition is always true, for example while(1) or for(;;). Note exit from such loops is effected with a break command (or return in a function). In nested loops an EXIT (in Ada) only causes the innermost repetition to terminate. For example in Ada suppose we were searching a 2-dimensional array A for the first occurrence of a certain value Wanted...

Find millions of documents on Course Hero - Study Guides, Lecture Notes, Reference Materials, Practice Exams and more. Course Hero has millions of course specific materials providing students with the best way to expand their education.

Below is a small sample set of documents:

East Los Angeles College - CS - 2130
CS2130 Programming Language Concepts and ParadigmsUnit 16 Object-Oriented Programming in Ada Tagged Types In the previous lecture we saw how a new type could be derived from an existing type and how such a type inherited the primitive operations of
East Los Angeles College - CS - 2130
CS2130 Programming Language Concepts and ParadigmsLecture 14 Generics In the previous lecture the package IntStack provided an abstract data object namely a stack of integers. It should be clear that the implementation of a stack of floating point n
East Los Angeles College - CS - 2130
CS2130 Programming Language Concepts and ParadigmsUnit 7 - More on Types Semi-Boolean Truth Values In some languages (for example C and C+, but not Java) there is no special Boolean type as such. Instead comparisons and other Boolean expressions pro
East Los Angeles College - CS - 2130
CS2130 Programming Language Concepts and ParadigmsUnit 3 - Values, Types and Variables The term value refers to anything that results when an expression is evaluated, or an entity that may be stored in a memory cell within the computer, or which for
East Los Angeles College - CS - 2130
CS2130 Programming Language Concepts and ParadigmsUnit 9 Concurrent Programming in Ada Tasks So far we have only considered sequential programs in which statements are obeyed in a single thread of control. However a program can also be built from tw
East Los Angeles College - CS - 2130
CS2130 Programming Language Concepts and ParadigmsUnit 6 Renaming in Ada It is possible to give a new name to certain Ada entities using a renaming declaration. The following entities can be renamed: variables constants array elements packages recor
East Los Angeles College - CS - 2130
CS2130 Programming Language Concepts and ParadigmsPractical Class 2 Solutions Solutions to the first lab class exercises may now be found on the module web-site and in the Unix directory ~barnesa/cs2130/lab1. Recall that you can access the module we
East Los Angeles College - CS - 2130
CS2130 Programming Language Concepts and ParadigmsPractical Class 1 The Module Web-site Check that you can access the module Web-site by following the CS2130 link from my home page with URLhttp:/www.aston.ac.uk/~barnesaor following the links Prog
East Los Angeles College - CS - 2130
CS2130 Programming Language Concepts and ParadigmsPractical Class 3 The Ada.Command_Line and POSIX.Files Packages The purpose of this lab is to introduce a few more of the Ada Libraries available with the Gnat Ada system. which enable an Ada program
Air Force Academy - ME - 475
f4_3f4_4
CSU Fullerton - OPS - 234
AS/400 Operations Navigator It is now possible for a user to execute AS/400 commands without having to learn Command Language syntax. Also, for those users who are aware of CL but feel more productive by pointing and clicking with a graphical interfa
East Los Angeles College - CS - 2130
7#&lt;#R#:#}#P#3#P#3#Q3# #Q=##QI#QW#QW#QW#QW##Qc# #Qm# #Qw#Qw#Qw#Qw#Qw# #Q#Qp#Q #Qe#Q#Q#,#Q#Q#Q #Q#Q#Q#Q# #Q#R# # # ##CS2130 Programming Language Concepts and ParadigmsUnit 9 Concurrent Programming in AdaTasksSo far we have only considered sequentia
East Los Angeles College - CS - 2130
7#|#:#v6#%#3# #3#3#.#a#$#I#w# #p## # # # # #,#&quot;##&amp;# (#,#0#2#6# # ## #CS2130 Programming Language Concepts and ParadigmsUnit 4 - Bindings and ScopeBindingEach time execution of a program in a high-level programming language such as Ada reaches a dec
Air Force Academy - ME - 324
Iron and Iron-Fe3C Equilibrium Phase DiagramIron (Fe) * Occurs naturally in meteorites. Only a small quantity is of terrestrial origin. * Is the second most abundant metal (after aluminium) in the Earths crust. It constitutes about 95% of all the me
East Los Angeles College - CS - 2130
7#\t# #Y #$#.# #.# .#&gt;#CN#&lt;\# \# \# \## h# # r# # |#R|# |# |#R|# # U# #d# # #7# # # #R# # #v# # # ## #CS2130 Programming Language Concepts and ParadigmsUnit 10 Synchronization in Concurrent Ada ProgramsProtected VariablesIn Ada 95 a simple mechanis
Air Force Academy - ME - 492
Department of Mechanical Engineering University of Saskatchewan ME464.3 MATERIALS IN ENGINEERING DESIGN Mid-Term Examination Instructor: I. Oguocha Date: 1 March, 2002.Instructions 1. Answer ALL Questions Time: 1 hours 2. Class notes are allowed. C
UMBC - PHYSICS - 151
Find the Angles An 82 kg traffic light is supported by two cables, one pulling up and to the right with 500 N, the other pulling up and to the left with 643 N. Find the angle which each cable makes with the horizontal.
Air Force Academy - ME - 492
ME492.3MaterialsinEngineeringDesign DepartmentofMechanicalEngineering UniversityofSaskatchewan ASSIGNMENT#1SOLUTIONJanuary2009 Question #1 Several professions claim to design one thing or another. Typical examples include: Fashion designer/tailor (de
Air Force Academy - ME - 229
AutoCAD 10% Progress report 5% Log book 10% Design report 25% Presentation 20% Final exam 30% Assignments P/F WHMIS P/F If you receive a F, marks will be withheld until a satisfactory performance has been achieved.Final MarksThe marks represent ra
Air Force Academy - ME - 229
Four Layered Spherical Display Structure:Panoramic Display of Lumieres PhotostereosynthesisGARNET HERTZ: DESIGN PROPOSALGarnet Hertz 1 January 2008 garnethertz@gmail.comAbstract: Proposal for building of a custom four-layered transparent spher
CSU Fullerton - GAM - 666
GAM666 Introduction To Game ProgrammingWindows Programming in C+ You must use special libraries (aka APIs application programming interfaces) to make something other than a text-based program. The C+ choices are: The original Windows SDK (Softwa
Air Force Academy - ME - 229
ME 229 AutoCAD SectionAssignment # 6 Draw the following drafts: Sizes of mechanical parts according to the dimension shown Lines and text are to be properly defined in different layers. Model geometry, dims and text in model space Use Papers
CSU Fullerton - SYA - 710
When One Billion does not equal One Billion, or: Why your computers disk drive capacity doesnt appear to match the stated capacityA White Paperby James Wiebe, CEO WiebeTech LLC www.wiebetech.com 2003 WiebeTech LLC This paper may be reproduced in
East Los Angeles College - CS - 1110
CS1110 Introduction to Systematic Programming Week 3 - Practical Class 1Compiler Error Messages and Compiler Listings So far we have assumed that when you compile an Ada program everything goes smoothly. However suppose that the source file ( divide
East Los Angeles College - CS - 1110
CS111 Introduction to Systematic Programming Second Practical ClassIf you did not attend the first practical or if you did not complete the worksheet, work through the hand-out for that practical BEFORE working on this sheet. Open the file prog1.adb
East Los Angeles College - CS - 1110
7#,#i# #h#.#!#.#(#.# .# .# .#&lt;#P# # #&quot;#4#L# #P#,# #x#(#D# $# # D# #*# # .## ]#I# #w#/#V# ##%#(# #Introduction to Systematic ProgrammingUnit 7 - Writing Larger Programs7.1 IntroductionThe first few units of this course have advocated a four stage ap
CSU Fullerton - INT - 428
1. Describe what the HTTP protocol is used for.HTTP is the protocol used to deliver hyptertext documents, images, and other data between web servers and web clients.2. (a) Which of the following colours are members of the so-called browsersafe pal
Air Force Academy - GE - 449
Presentation Outline1. The GapTechnology and Sustainable DevelopmentGE 449Lisa White Chris Richards2. Global Sustainability 3. The Scala Project in the Philippines 4. The Multifunctional Platform in Ghana 5. Workshop Shea Butter in West Afric
East Los Angeles College - CS - 3250
CS3250 Distributed Systems1. a) Describe how the Transmission Control Protocol (TCP) provides a reliable connection-oriented service on top of the unreliable connectionless service provided by the Internet Protocol (IP). In your answer you should i
East Los Angeles College - CS - 3250
CS3250 Distributed SystemsLecture 6 - More on TCP/IP Delay or Loss of Data Segments In the left-hand diagram below host 1 sends a data segment containing n octets of data with sequence number X1 and when this arrives at host 2, an acknowledgement is
East Los Angeles College - CS - 3250
CS3250 Distributed SystemsLecture 13 A Server Which Reuses Idle tasks The multi-threaded server in lecture 11 created a new task for each client connection. This task becomes idle when the client that it is serving terminates the interaction by ente
Air Force Academy - GE - 111
Cramers RuleCRAMERS RULEGE 111 Engineering Problem Solving 20081Cramers RuleGabriel Cramer was a Swiss mathematician (1704-1752)GE 111 Engineering Problem Solving 20082Coefficient Matrices You can use determinants to solve a system o
East Los Angeles College - CS - 3250
CS3250 Distributed SystemsLecture 9 Client-Server Communication Protocols To date in the lecture and practical class examples the services provided by the server programs have been quite simple; we have primarily been concerned with issues such as:
CSU Fullerton - INT - 428
AgendaReview Perl Quoting Regular expressions Break! Perl Stringwise operators Context FunctionsSeneca College - INT428 Perl June 11, 2002Perl - reviewPerl - QuotingA Perl statement can have a &quot;modifier&quot; placed on the end of it. What are so
East Los Angeles College - CS - 3250
CS3250 Distributed SystemsLecture 10 Multi-threaded Servers In previous lectures and practicals we have seen a number of simple client-server programs communicating via sockets. In these examples the server dealt with the client request itself compl
East Los Angeles College - CS - 3250
CS3250 Distributed SystemsLab Class 8 Copy the Ada source files for this class as follows:cp ~barnesa/cs325/lab8/*.ad[sb] linuxwhere linux is some directory in your own user area. The package NetUtils (files netutils.ads and netutils.adb) contain
CSU Fullerton - INT - 428
AgendaReview Perl Statements BlocksSeneca College - INT428 Perl June 6, 2002Break! Perl Operators Quoting Regular expressions FunctionsPerl - reviewPerl - SyntaxWhat is normally on the first line of a Perl program? What is a pragma? What
CSU Fullerton - INT - 428
AgendaReview More control of framesSeneca College - INT428 HTML Frames May 28, 2002Break! FormsReview - FramesReview - FramesFrames divide the screen into multiple, &quot;independent&quot; regions Each region is loaded from a separate file and has
Air Force Academy - AE - 495
AB E 495.3 Design Capstone IIClass Information This Page contains: Course Outline Location Evaluation Prerequisites Texts Instructor Course Outline Official Calendar Descriptions A continuation of AB E 395 in a self-directed course. Students perform
Air Force Academy - ABE - 395
Bourgault Industries Ltd. #104 116 Research Drive Saskatoon, Sask. S7N 3R3Design Project: Analysis of the Shank Used on Air Hoe Drills and Other Tillage EquipmentThe project would involve an analysis of the shank that we use on our air hoe drills
East Los Angeles College - CS - 3250
CS3250 Distributed SystemsLab Class 7 The directory ~barnesa/cs325/lab7 contains a number of example programs: 1. an Ada client client.adb which uses a stream socket to contact either of the servers described below. The client is invoked with a comm
East Los Angeles College - CS - 3250
CS3250 Distributed SystemsLab Class 6 Gnat Datagram Sockets Although a datagram socket can be used for an extended conversation, more usually they are used for 'one-shot' messages and replies. We could have implemented the simple `talk' program in l
East Los Angeles College - CS - 3250
CS3250 Distributed SystemsLab Class 1 In this lab class you should familiarize yourself with the new Linux systems the desk-top environment KDE the Gnat Ada system on Linux the use of either Emacs or GPS as an IDE for Ada. Linux The machines in MB20
East Los Angeles College - CS - 3250
CS3250 Distributed SystemsLab Class 3Solutions for the exercises in lab 2 are available on the module Web-site and in the UNIX directory~barnesa/CS325/lab2/Note: When debugging a program which produces binary files, it may be necessary to view
East Los Angeles College - CS - 3250
CS3250 Distributed SystemsLab Class 5 Gnat Sockets In this lab we will look at an Ada implementation of a simple &quot;talk&quot; program Copy the files~barnesa/cs325/lab5/*.adbto your own user area. These files are also available on the module web-site. O
East Los Angeles College - CS - 3250
CS3250 Distributed SystemsLecture 6 - More on TCP/IP Delay or Loss of Data Segments In the left-hand diagram below host 1 sends a data segment containing n octets of data with sequence number X1 and when this arrives at host 2, an acknowledgement is
East Los Angeles College - CS - 3250
CS3250 Distributed SystemsLecture 13 Client-Server Communication Protocols To date in the lecture and practical class examples the services provided by the server programs have been quite simple; we have primarily been concerned with issues such as:
East Los Angeles College - CS - 3250
CS3250 Distributed SystemsLab Class 8 In this lab and the next lab class we will be looking at some simple Ada distributed programs partitioned using the facilities of the distributed systems annex and then configured (and allocated) using gnatdist
East Los Angeles College - CS - 3250
CS3250 Distributed SystemsLab Class 5 Gnat Datagram Sockets In this lab we will look first at an Ada implementation of a simple &quot;talk&quot; program using a datagram socket rather than a stream socket (as was used in the lab class last week). Copy the fil
East Los Angeles College - CS - 3250
CS3250 Distributed SystemsLab Class 10 In this lab we will continue to look at some simple Ada distributed programs partitioned using the facilities of the distributed systems annex and then configured (and allocated) using gnatdist from the Gnat GL
East Los Angeles College - CS - 3250
CS3250 Distributed SystemsLab Class 4 Inter-process Communication with FIFOs In the module CS2230 Operating Systems inter-process communication with pipes were considered. Pipes have their uses and for example are used extensively by UNIX shells to
East Los Angeles College - CS - 3250
CS3250 Distributed SystemsLab Class 6 The directory ~barnesa/cs325/lab6 contains a number of example programs: 1. an Ada client client.adb which uses a stream socket to contact either of the servers described below. The client is invoked with a comm
East Los Angeles College - CS - 3250
CS3250 Distributed SystemsLab Class 3 Inter-process Communication with FIFOs In the module CS2230 Operating Systems inter-process communication with pipes were considered. Pipes have their uses and for example are used extensively by UNIX shells to
East Los Angeles College - CS - 3250
CS3250 Distributed SystemsLab Class 2Solutions for the exercises in lab 1 are available on the module Web-site and in the UNIX directory~barnesa/CS325/lab1/Note: When debugging a program which produces binary files, it may be necessary to view
East Los Angeles College - CS - 3250
Lab Class 3 Problem 1Due to a bug in the latest version of the Ada compiler, programs which attempt to use the stream IO attributes Input and Output for LIMITED PRIVATE types will not compile. There is no problem with the attributes Read and Write.
East Los Angeles College - CS - 3250
CS3250 Distributed SystemsLab Class 9 In this lab we will continue at some simple Ada distributed programs partitioned using the facilities of the distributed systems annex and then configured (and allocated) using gnatdist from the Gnat GLADE syste
East Los Angeles College - CS - 3250
CS3250 Distributed SystemsLab Class 4 Gnat Sockets In this lab we will look at an Ada implementation of a simple &quot;talk&quot; program Copy the files~barnesa/cs325/lab4/*.adbto your own user area. Outline of client &amp; server structures Inspect the source
East Los Angeles College - CS - 3250
CS3250 Distributed SystemsLab Class 7 Three model solutions for last week's lab. exercise may be found in the directory:~barnesa/cs325/lab6/solution/One use Check_Selector to check for the arrival of incoming connection requests before calling Ac
East Los Angeles College - CS - 3250
CS3250 Distributed SystemsLab Class 9 In this lab and the next lab class we will be looking at some simple Ada distributed programs partitioned using the facilities of the distributed systems annex and then configured (and allocated) using gnatdist
East Los Angeles College - CS - 3250
CS3250 Distributed SystemsLab Class 3Solutions for the exercises in lab 2 are available on the module Web-site and in the UNIX directory~barnesa/CS325/lab2/Note: When debugging a program which produces binary files, it may be necessary to view
Air Force Academy - ABE - 322
Chapter II Numerical Integration Defining: I =abf ( x)dx I denotes the shaded area enclosed between the curve y=f(x) and the x-axis. Trapezoidal Rule Simpsons Rule (most popular) Monte Carlo Method (less accurate, simple)Trapezoidal R