# NRI Institute of Technology Principles of Programming Languages III B.Tech I Sem (R09)-CSE

Save this PDF as:

Size: px
Start display at page:

Download "NRI Institute of Technology Principles of Programming Languages III B.Tech I Sem (R09)-CSE"

## Transcription

1 Unit-4 Expressions and Assignment Statements Introduction Expressions are the fundamental means of specifying computations in a programming language. To understand expression evaluation, need to be familiar with the orders of operator and operand evaluation. Essence of imperative languages is dominant role of assignment statements. Arithmetic Expressions Their evaluation was one of the motivations for the development of the first programming languages. Most of the characteristics of arithmetic expressions in programming languages were inherited from conventions that had evolved in math. Arithmetic expressions consist of operators, operands, parentheses, and function calls. The operators can be unary, or binary. C-based languages include a ternary operator. The purpose of an arithmetic expression is to specify an arithmetic computation. An implementation of such a computation must cause two actions: o Fetching the operands from memory o Executing the arithmetic operations on those operands. Design issues for arithmetic expressions: 1. What are the operator precedence rules? 2. What are the operator associativity rules? 3. What is the order of operand evaluation? 4. Are there restrictions on operand evaluation side effects? 5. Does the language allow user-defined operator overloading? 6. What mode mixing is allowed in expressions? Operator Evaluation Order 1. Precedence 1. The operator precedence rules for expression evaluation define the order in which adjacent operators of different precedence levels are evaluated ( adjacent means they are separated by at most one operand). 2. Typical precedence levels: 1. parentheses 2. unary operators 3. ** (if the language supports it) 4. *, / 5. +, - 3. Many languages also include unary versions of addition and subtraction. 4. Unary addition is called the identity operator because it usually has no associated operation and thus has no effect on its operand. 5. In Java, unary plus actually does have an effect when its operand is short or byte. An implicit conversion of short and byte operands to int type takes place. 6. Ex: Prepared by A.Sharath Kumar, Sr. Asst. Prof, CSE 1

2 A + (- B) * C A + - B * C // is legal // is illegal 2. Associativity The operator associativity rules for expression evaluation define the order in which adjacent operators with the same precedence level are evaluated. An operator can be either left or right associative. Typical associativity rules: o Left to right, except **, which is right to left o Sometimes unary operators associate right to left (e.g., FORTRAN) Ex: (Java) a b + c // left to right Ex: (Fortran) A ** B ** C // right to left (A ** B) ** C // In Ada it must be parenthesized Language Associativity Rule FORTRAN Left: * / + - Right: ** C-BASED LANGUAGES Left: * / % binary + binary - Right: unary unary + ADA Left: all except ** Non-associative: ** APL is different; all operators have equal precedence and all operators associate right to left. Ex: A X B + C // A = 3, B = 4, C = 5 27 Precedence and associativity rules can be overridden with parentheses. Prepared by A.Sharath Kumar, Sr. Asst. Prof, CSE 2

3 3. Parentheses Programmers can alter the precedence and associativity rules by placing parentheses in expressions. A parenthesized part of an expression has precedence over its adjacent un-parenthesized parts. Ex: (A + B) * C 4. Conditional Expressions Sometimes if-then-else statements are used to perform a conditional expression assignment. if (count == 0) average = 0; else average = sum / count; In the C-based languages, this can be specified more conveniently in an assignment statement using a conditional expressions average = (count == 0)? 0 : sum / count; Operand evaluation order 1. Side Effects The process: 1. Variables: just fetch the value from memory. 2. Constants: sometimes a fetch from memory; sometimes the constant is in the machine language instruction. 3. Parenthesized expressions: evaluate all operands and operators first. A side effect of a function, called a functional side effect, occurs when the function changes either one of its parameters or a global variable. Ex: a + fun(a) If fun does not have the side effect of changing a, then the order of evaluation of the two operands, a and fun(a), has no effect on the value of the expression. However, if fun changes a, there is an effect. Ex: Consider the following situation: fun returns the value of its argument divided by 2 and changes its parameter to have the value 20, and: a = 10; b = a + fun(a); If the value of a is returned first (in the expression evaluation process), its value is 10 and the value of the expression is 15. Prepared by A.Sharath Kumar, Sr. Asst. Prof, CSE 3

5 Type Conversions A narrowing conversion is one that converts an object to a type that cannot include all of the values of the original type e.g., float to int. A widening conversion is one in which an object is converted to a type that can include at least approximations to all of the values of the original type e.g., int to float. Coercion in Expressions A mixed-mode expression is one that has operands of different types. A coercion is an implicit type conversion. The disadvantage of coercions: They decrease in the type error detection ability of the compiler In most languages, all numeric types are coerced in expressions, using widening conversions Language are not in agreement on the issue of coercions in arithmetic expressions. Those against a broad range of coercions are concerned with the reliability problems that can result from such coercions, because they eliminate the benefits of type checking. Those who would rather include a wide range of coercions are more concerned with the loss in flexibility that results from restrictions. The issue is whether programmers should be concerned with this category of errors or whether the compiler should detect them. Ex: void mymethod() { int a, b, c; float d; a = b * d; Assume that the second operand was supposed to be c instead of d. Because mixed-mode expressions are legal in Java, the compiler wouldn t detect this as an error. Simply, b will be coerced to float. Prepared by A.Sharath Kumar, Sr. Asst. Prof, CSE 5

6 Explicit Type Conversions Often called casts in C-based languages. Ex: Ada: FLOAT(INDEX)--INDEX is INTEGER type Java: (int)speed /*speed is float type*/ Errors in Expressions Caused by: Inherent limitations of arithmetic e.g. division by zero Limitations of computer arithmetic e.g. overflow or underflow Such errors are often ignored by the run-time system. Relational and Boolean Expressions Relational Expressions: has two operands and one relational operator. The value of a relational expression is Boolean, unless it is not a type included in the language. Use relational operators and operands of various types. Operator symbols used vary somewhat among languages (!=, /=,.NE., <>, #) The syntax of the relational operators available in some common languages is as follows: Operation Ada C-Based Languages Fortran 95 Equal = ==.EQ. or == Not Equal /=!=.NE. or <> Greater than > >.GT. or > Less than < <.LT. or < Greater than or equal >= >=.GE. or >= Less than or equal <= <=.LE. or >= Prepared by A.Sharath Kumar, Sr. Asst. Prof, CSE 6

7 Boolean Expressions Operands are Boolean and the result is Boolean. FORTRAN 77 FORTRAN 90 C Ada.AND. and && and.or. or or.not. not! not Versions of C prior to C99 have no Boolean type; it uses int type with 0 for false and nonzero for true. One odd characteristic of C s expressions: a < b < c is a legal expression, but the result is not what you might expect. The left most operator is evaluated first b/c the relational operators of C, are left associative, producing either 0 or 1. Then this result is compared with var c. There is never a comparison between b and c. Short Circuit Evaluation A short-circuit evaluation of an expression is one in which the result is determined without evaluating all of the operands and/or operators. Ex: (13 * a) * (b/13 1) // is independent of the value (b/13 1) if a = 0, b/c 0*x = 0. So when a = 0, there is no need to evaluate (b/13 1) or perform the second multiplication. However, this shortcut is not easily detected during execution, so it is never taken. The value of the Boolean expression: (a >= 0) && (b < 10) // is independent of the second expression if a < 0, b/c (F && x) is False for all the values of x. So when a < 0, there is no need to evaluate b, the constant 10, the second relational expression, or the && operation. Unlike the case of arithmetic expressions, this shortcut can be easily discovered during execution. Short-circuit evaluation exposes the potential problem of side effects in expressions (a > b) (b++ / 3) // b is changed only when a <= b. If the programmer assumed b would change every time this expression is evaluated during execution, the program will fail. C, C++, and Java: use short-circuit evaluation for the usual Boolean operators (&& and ), but also provide bitwise Boolean operators that are not short circuit (& and ) Prepared by A.Sharath Kumar, Sr. Asst. Prof, CSE 7

8 Assignment Statements Simple Assignments The C-based languages use == as the equality relational operator to avoid confusion with their assignment operator. The operator symbol for assignment: 1. = FORTRAN, BASIC, PL/I, C, C++, Java 2. := ALGOL, Pascal, Ada Conditional Targets Ex: flag? count 1 : count2 = 0; if (flag) count1 = 0; else count2 = 0; Compound Assignment Operators A compound assignment operator is a shorthand method of specifying a commonly needed form of assignment. The form of assignment that can be abbreviated with this technique has the destination var also appearing as the first operand in the expression on the right side, as in a = a + b The syntax of assignment operators that is the catenation of the desired binary operator to the = operator. sum += value; sum = sum + value; Unary Assignment Operators C-based languages include two special unary operators that are actually abbreviated assignments. They combine increment and decrement operations with assignments. The operators ++ and -- can be used either in expression or to form stand-alone single-operator assignment statements. They can appear as prefix operators: sum = ++ count; count = count + 1; sum = count; Prepared by A.Sharath Kumar, Sr. Asst. Prof, CSE 8

9 If the same operator is used as a postfix operator: sum = count ++; sum = count; count = count + 1; Assignment as an Expression This design treats the assignment operator much like any other binary operator, except that it has the side effect of changing its left operand. Ex: while ((ch = getchar())!=eof) { // why ( ) around assignment? The assignment statement must be parenthesized b/c the precedence of the assignment operator is lower than that of the relational operators. Disadvantage: o Another kind of expression side effect which leads to expressions that are difficult to read and understand. There is a loss of error detection in the C design of the assignment operation that frequently leads to program errors. if (x = y) instead of if (x == y) Mixed-Mode Assignment In FORTRAN, C, and C++, any numeric value can be assigned to any numeric scalar variable; whatever conversion is necessary is done. In Pascal, integers can be assigned to reals, but reals cannot be assigned to integers (the programmer must specify whether the conversion from real to integer is truncated or rounded.) In Java, only widening assignment coercions are done. In Ada, there is no assignment coercion. In all languages that allow mixed-mode assignment, the coercion takes place only after the right side expression has been evaluated. Prepared by A.Sharath Kumar, Sr. Asst. Prof, CSE 9

10 Control Statements: Introduction A control structure is a control statement and the statements whose execution it controls. Overall Design Question: o What control statements should a language have, beyond selection and pretest logical loops? Selection Statements A selection statement provides the means of choosing between two or more paths of execution. Two general categories: o Two-way selectors o Multiple-way selectors Two-Way Selection Statements The general form of a two-way selector is as follows: if control_expression then clause else clause 1. Design issues What is the form and type of the control expression? How are the then and else clauses specified? How should the meaning of nested selectors be specified? 2. The control Expression Control expressions are specified in parenthesis if the then reserved word is not used to introduce the then clause, as in the C-based languages. In C89, which did not have a Boolean data type, arithmetic expressions were used as control expressions. In contemporary languages, such as Java and C#, only Boolean expressions can be used for control expressions. Prior to FORTRAN95 IF: IF (boolean_expr) statement Problem: can select only a single statement; to select more, a GOTO must be used, as in the following example IF (.NOT. condition) GOTO CONTINUE Prepared by A.Sharath Kumar, Sr. Asst. Prof, CSE 10

11 Clause Form In most contemporary languages, the then and else clauses either appear as single statements or compound statements. C-based languages use braces to form compound statements. In Ada the last clause in a selection construct is terminated with end and if. Nesting Selectors In Java and contemporary languages, the static semantics of the language specify that the else clause is always paired with the nearest unpaired then clause. if (sum == 0) if (count == 0) result = 0; else result = 1; A rule, rather than a syntactic entity, is used to provide the disambiguation. So in the above example, the else clause would be the alternative to the second then clause. To force the alternative semantics in Java, a different syntactic form is required, in which the inner if-then is put in a compound, as in if (sum == 0) { if (count == 0) result = 0; else result = 1; C, C++, and C# have the same problem as Java with selection statement nesting. Multiple Selection Constructs The multiple selection construct allows the selection of one of any number of statements or statement groups. Design Issues What is the form and type of the control expression? How are the selectable segments specified? Is execution flow through the structure restricted to include just a single selectable segment? What is done about unrepresented expression values? Prepared by A.Sharath Kumar, Sr. Asst. Prof, CSE 11

12 Examples of Multiple Selectors The C, C++, and Java switch switch (expression) { case constant_expression_1 : statement_1;... case constant_expression_n : statement_n; [default: statement_n+1] The control expression and the constant expressions are integer type. The switch construct does not provide implicit branches at the end of those code segments. Selectable segments can be statement sequences, blocks, or compound statements. Any number of segments can be executed in one execution of the construct (a trade-off between reliability and flexibility convenience.) To avoid it, the programmer must supply a break statement for each segment. default clause is for unrepresented values (if there is no default, the whole statement does nothing.) C# switch statement rule disallows the implicit execution of more than one segment. The rule is that every selectable segment must end with an explicit unconditional branch statement, either a break, which transfers control out of the switch construct, or a goto, which can transfer control to on of the selectable segments. switch (value) { case -1: Negatives++; break; case 0: Positives++; goto case 1; case 1: Positives ++; default: Console.WriteLine( Error in switch \n ); Multiple Selection Using if Early Multiple Selectors: o FORTRAN arithmetic IF (a three-way selector) IF (arithmetic expression) N1, N2, N3 Bad aspects: o Not encapsulated (selectable segments could be anywhere) o Segments require GOTOs o FORTRAN computed GOTO and assigned GOTO To alleviate the poor readability of deeply nested two-way selectors, Ada has been extended specifically for this use. Prepared by A.Sharath Kumar, Sr. Asst. Prof, CSE 12

13 If Count < 10 then Bag1 := True; elsif Count < 100 then Bag2 := True; elsif Count < 1000 then Bag3 := True; end if; if Count < 10 then Bag1 := True; else if Count < 100 then Bag2 := True; else if Count < 1000 then Bag3 := True; end if; end if; end if; The elsif version is the more readable of the two. This example is not easily simulated with a case statement, b/c each selectable statement is chosen on the basis of a Boolean expression. Iterative Statement The repeated execution of a statement or compound statement is accomplished by iteration zero, one, or more times. Iteration is the very essence of the power of computer. The repeated execution of a statement is often accomplished in a functional language by recursion rather then by iteration. General design issues for iteration control statements: 1. How is iteration controlled? 2. Where is the control mechanism in the loop? The primary possibilities for iteration control are logical, counting, or a combination of the two. The main choices for the location of the control mechanism are the top of the loop or the bottom of the loop. The body of a loop is the collection of statements whose execution is controlled by the iteration statement. The term pretest means that the loop completion occurs before the loop body is executed. The term posttest means that the loop completion occurs after the loop body is executed. The iteration statement and the associated loop body together form an iteration construct. Prepared by A.Sharath Kumar, Sr. Asst. Prof, CSE 13

14 Counter-Controlled Loops A counting iterative control statement has a var, called the loop var, in which the count value is maintained. It also includes means of specifying the intial and terminal values of the loop var, and the difference between sequential loop var values, called the stepsize. The intial, terminal and stepsize are called the loop parameters. Design Issues: What are the type and scope of the loop variable? What is the value of the loop variable at loop termination? Should it be legal for the loop variable or loop parameters to be changed in the loop body, and if so, does the change affect loop control? Should the loop parameters be evaluated only once, or once for every iteration? FORTRAN 90 s DO Syntax: DO label variable = initial, terminal [, stepsize] END DO [name] The label is that of the last statement in the loop body, and the stepsize, when absent, defaults to 1. Loop variable must be an INTEGER and may be either negative or positive. The loop params are allowed to be expressions and can have negative or positive values. They are evaluated at the beginning of the execution of the DO statement, and the value is used to compute an iteration count, which then has the number of times the loop is to be executed. The loop is controlled by the iteration count, not the loop param, so even if the params are changed in the loop, which is legal, those changes cannot affect loop control. The iteration count is an internal var that is inaccessible to the user code. The DO statement is a single-entry structure. The for Statement of the C-Based Languages Syntax: for ([expr_1] ; [expr_2] ; [expr_3]) statement loop body The loop body can be a single statement, a compound statement, or a null statement. for (i = 0, j = 10; j == i; i++) All of the expressions of C s for are optional. If the second expression is absent, it is an infinite loop. If the first and third expressions are absent, no assumptions are made. The C for design choices are: 1. There are no explicit loop variable or loop parameters. 2. All involved vars can be changed in the loop body. 3. It is legal to branch into a for loop body despite the fact that it can create havoc. C s for is more flexible than the counting loop statements of Fortran and Ada, b/c each of the expressions can comprise multiple statements, which in turn allow multiple loop vars that can be of any type. Prepared by A.Sharath Kumar, Sr. Asst. Prof, CSE 14

15 Consider the following for statement: for (count1 = 0, count2 = 1.0; count1 <= 10 && count2 <= 100.0; sum = ++count1 + count2, count2 *= 2.5); The operational semantics description of this is: count1 = 0 count2 = 1.0 loop: if count1 > 10 goto out if count2 > goto out count1 = count1 + 1 sum = count1 + count2 count2 = count2 * 2.5 goto loop out The loop above does not need and thus does not have a loop body. C99 and C++ differ from earlier version of C in two ways: 1. It can use a Boolean expression for loop control. 2. The first expression can include var definitions. Logically Controlled Loops Design Issues: 1. Pretest or posttest? 2. Should this be a special case of the counting loop statement (or a separate statement)? C and C++ also have both, but the control expression for the posttest version is treated just like in the pretest case (while - do and do - while) These two statements forms are exemplified by the following C# code: sum = 0; indat = Console.ReadLine( ); while (indat >= 0) { sum += indat; indat = Console.ReadLine( ); value = Console.ReadLine( ); do { value /= 10; digits ++; while (value > 0); Prepared by A.Sharath Kumar, Sr. Asst. Prof, CSE 15

16 The only real difference between the do and the while is that the do always causes the loop body to be executed at least once. Java does not have a goto, the loop bodies cannot be entered anywhere but at their beginning. User-Located Loop Control Mechanisms It is sometimes convenient for a programmer to choose a location for loop control other than the top or bottom of the loop. Design issues: 1. Should the conditional be part of the exit? 2. Should control be transferable out of more than one loop? C and C++ have unconditional unlabeled exits (break). Java, Perl, and C# have unconditional labeled exits (break in Java and C#, last in Perl). The following is an example of nested loops in C#: OuterLoop: for (row = 0; row < numrows; row++) for (col = 0; col < numcols; col++) { sum += mat[row][col]; if (sum > ) break outerloop; C and C++ include an unlabeled control statement, continue, that transfers control to the control mechanism of the smallest enclosing loop. This is not an exit but rather a way to skip the rest of the loop statements on the current iteration without terminating the loop structure. Ex: while (sum < 1000) { getnext(value); if (value < 0) continue; sum += value; A negative value causes the assignment statement to be skipped, and control is transferred instead to the conditional at the top of the loop. On the other hand, in Prepared by A.Sharath Kumar, Sr. Asst. Prof, CSE 16

17 while (sum < 1000) { getnext(value); if (value < 0) break; sum += value; A negative value terminates the loop. Java, Perl, and C# have statements similar to continue, except they can include labels that specify which loop is to be continued. The motivation for user-located loop exits is simple: They fulfill a common need for goto statements through a highly restricted branch statement. The target of a goto can be many places in the program, both above and below the goto itself. However, the targets of user-located loop exits must be below the exit and can only follow immediately the end of a compound statement. Iteration Based on Data Structures Concept: use order and number of elements of some data structure to control iteration. C# s foreach statement iterates on the elements of array and other collections. String[ ] strlist = { Bob, Carol, Ted, Beelzebub ; foreach (String name in strlist) Console.WriteLine( Name: {0, name); The notation {0 in the parameter to Console.WriteLine above indicates the position in the string to be displayed where the value of the first named variable, name in this example, is to be placed. Control mechanism is a call to a function that returns the next element in some chosen order, if there is one; else exit loop C's for can be used to build a user-defined iterator. The iterator is called at the beginning of each iteration, and each time it is called, the iterator returns an element from a particular data structure in some specific order. Unconditional Branching An unconditional branch statement transfers execution control to a specified place in the program. Problems with Unconditional Branching The unconditional branch, or goto, is the most powerful statement for controlling the flow of execution of a program s statements. However, using the goto carelessly can lead to serious problems. Without restrictions on use, imposed either by language design or programming standards, goto statements can make programs virtually unreadable, and as a result, highly unreliable and difficult to maintain. There problems follow directly from a goto s capability of forcing any program statement to follow any other in execution sequence, regardless of whether the statement proceeds or follows the first in textual order. Java doesn t have a goto. However, most currently popular languages include a goto statement. C# uses goto in the switch statement. Prepared by A.Sharath Kumar, Sr. Asst. Prof, CSE 17

### Chapter 8 Statement-Level Control Structures Chapter 8 Topics

Chapter 8 Statement-Level Control Structures Chapter 8 Topics Introduction Selection Statements Iterative Statements Unconditional Branching Chapter 8 Statement-Level Control Structures Introduction A

### Organization of Programming Languages CS3200 / 5200N. Lecture 07

Organization of Programming Languages CS3200 / 5200N Razvan C. Bunescu School of Electrical Engineering and Computer Science bunescu@ohio.edu Control Flow Control flow = the flow of control, or execution

### Chapter 8. Statement-Level Control Structures ISBN

Chapter 8 Statement-Level Control Structures ISBN 0-321-33025-0 Chapter 8 Topics Introduction Selection Statements Iterative Statements Unconditional Branching Guarded Commands Conclusions Copyright 2006

### Chapter 8. Statement-Level Control Structures

Chapter 8 Statement-Level Control Structures Chapter 8 Topics Introduction Selection Statements Iterative Statements Unconditional Branching Guarded Commands Conclusions 8-2 1 Levels of Control Flow Within

### Software II: Principles of Programming Languages

Software II: Principles of Programming Languages Lecture 8 Statement-Level Control Structures Control Statements: Evolution FORTRAN I control statements were based directly on IBM 704 hardware Much research

### Iterative Statements. 1. How is iteration controlled? 2. Where is the control mechanism in the loop? Logical expression or counter.

Iterative Statements The repeated execution of a statement or compound statement is accomplished either by iteration or recursion General design issues for iteration control statements: 1. How is iteration

### Organization of Programming Languages CS3200 / 5200N. Lecture 08

Organization of Programming Languages CS3200 / 5200N Razvan C. Bunescu School of Electrical Engineering and Computer Science bunescu@ohio.edu Control Flow Control flow = the flow of control, or execution

### Statement-Level Control Structures

Statement-Level Control Structures Introduction Selection Statements Iterative Statements Unconditional Branching Levels of Control Flow Within expressions Among program units Among program statements

### Chapter 5 Names, Bindings, Type Checking, and Scopes

Chapter 5 Names, Bindings, Type Checking, and Scopes Chapter 5 Topics Introduction Names Variables The Concept of Binding Type Checking Strong Typing Scope Scope and Lifetime Referencing Environments Named

### Exam objectives. Java Certification - Week 2. Operators and Assignments. Chris Harris. Overview. Exam objectives (continued)

Exam objectives Java Certification - Week 2 Operators and Assignments Chris Harris Determine the result of applying any operator,including assignment operators,instance of,and casts to operands of any

### Chapter 4 Operators & Arithmetic

Chapter 4 Operators & Arithmetic 4-1 Arithmetic in C++ Arithmetic expressions can be made up of constants, variables, operators and parentheses. The arithmetic operators in C++ are as follows + (addition)

### The PCAT Programming Language Reference Manual

The PCAT Programming Language Reference Manual Andrew Tolmach and Jingke Li Dept. of Computer Science Portland State University (revised October 8, 2004) 1 Introduction The PCAT language (Pascal Clone

### Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Embedded Systems A Review of ANSI C and Considerations for Embedded C Programming Dr. Jeff Jackson Lecture 2-1 Review of ANSI C Topics Basic features of C C fundamentals Basic data types Expressions Selection

### Two-way selection. Branching and Looping

Control Structures: are those statements that decide the order in which individual statements or instructions of a program are executed or evaluated. Control Structures are broadly classified into: 1.

### 6.096 Lab 1. Due: 7 January 12:30:00. September 20, 2011

6.096 Lab 1 Due: 7 January 1:30:00 September 0, 011 1 Additional Material 1.1 Constants A constant is an expressions with a fixed value. Kinds of constants: Literals: used to express particular values

### 14 MAKING DECISIONS IN C

14 MAKING DECISIONS IN C 14.1 INTRODUCTION So far we have seen that in C programs the instructions are executed in the same order in which they appear in the program. Each instruction is executed once

### School of Informatics, University of Edinburgh

CS1Ah Lecture Note 5 Java Expressions Many Java statements can contain expressions, which are program phrases that tell how to compute a data value. Expressions can involve arithmetic calculation and method

### Object Oriented Software Design

Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa September 14, 2011 G. Lipari (Scuola Superiore Sant Anna) Introduction

### Control Structure. Pseudocode: Input number If number is even Then Print even Else print odd. Flowchart: Begin. End. Print Odd. number even?

Control Structure Normally, a program is executed in a sequential manner.however, in many cases, a program has to choose among alternative statements C++ provides constructs that enable the programmer

### Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

1. Explain C tokens Tokens are basic building blocks of a C program. A token is the smallest element of a C program that is meaningful to the compiler. The C compiler recognizes the following kinds of

### Java Review (Essentials of Java for Hadoop)

Java Review (Essentials of Java for Hadoop) Have You Joined Our LinkedIn Group? What is Java? Java JRE - Java is not just a programming language but it is a complete platform for object oriented programming.

### C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 2: Basic Elements of C++

C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with the basic components of a C++ program,

### Object Oriented Software Design

Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 28, 2010 G. Lipari (Scuola Superiore Sant Anna) Introduction

### Borland C++ Compiler: Operators

Introduction Borland C++ Compiler: Operators An operator is a symbol that specifies which operation to perform in a statement or expression. An operand is one of the inputs of an operator. For example,

### Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Name: Class: Date: Exam #1 - Prep True/False Indicate whether the statement is true or false. 1. Programming is the process of writing a computer program in a language that the computer can respond to

### Punctuation in C. Identifiers and Expressions. Identifiers. Variables. Keywords. Identifier Examples

Identifiers and Expressions CSE 130: Introduction to C Programming Spring 2005 Punctuation in C Statements are terminated with a ; Groups of statements are enclosed by curly braces: { and } Commas separate

### JavaScript: Control Statements I

1 7 JavaScript: Control Statements I 7.1 Introduction 2 The techniques you will learn here are applicable to most high-level languages, including JavaScript 1 7.2 Algorithms 3 Any computable problem can

### switch Multiple-Selection Statement

switch Multiple-Selection Statement (This feature is rarely useful, although it s perfect for programming the iterative song The Twelve Days of Christmas!) If no match occurs, the default case is executed,

### Ordering Program Execution: What is Done First? Control Flow. Expression Evaluation. Expression Evaluation Ordering: Precedence and Associativity

Control Flow In this set of notes you will learn about: Expression evaluation order Assignments Structured and unstructured flow Goto s Sequencing Selection Iteration Recursion Copyright R.A. van Engelen,

### 3) Do you think the elimination of overloaded operators in your favorite language would be beneficial? Why or why not? Answer:

Chapter 7: (Problem Set: Pages 306 308) 3) Do you think the elimination of overloaded operators in your favorite language would be beneficial? Why or why not? - Yes, I think that the elimination of overloaded

### Chapter 2: Elements of Java

Chapter 2: Elements of Java Basic components of a Java program Primitive data types Arithmetic expressions Type casting. The String type (introduction) Basic I/O statements Importing packages. 1 Introduction

### Moving from CS 61A Scheme to CS 61B Java

Moving from CS 61A Scheme to CS 61B Java Introduction Java is an object-oriented language. This document describes some of the differences between object-oriented programming in Scheme (which we hope you

### Chapter 8 Topics. Chapter 8. Levels of Control Flow. Evolution of Control Statements. Control Structures. Goto Statement

Chapter 8 Topics Chapter 8 Statement-Level Control Structures Introduction Selection Statements Iterative Statements Unconditional Branching Guarded Commands Conclusions Levels of Control Flow Within expressions

### VB.NET Programming Fundamentals

Chapter 3 Objectives Programming Fundamentals In this chapter, you will: Learn about the programming language Write a module definition Use variables and data types Compute with Write decision-making statements

### Java How to Program, 9/e

Java How to Program, 9/e Education, Inc. All Rights Reserved. 1 Any computing problem can be solved by executing a series of actions in a specific order. An algorithm is a procedure for solving a problem

### ,!7IA3C1-dcahfj!:t;K;k;K;k. Addison-Wesley s JavaScript Reference Card. Kathleen M. Goelz and Carol J. Schwartz, Rutgers University VARIABLES

Addison-Wesley s JavaScript Reference Card Kathleen M. Goelz and Carol J. Schwartz, Rutgers University Javascript: A scripting language designed to be integrated into HTML code to produce enhanced, dynamic,

### Chapter 5. Selection 5-1

Chapter 5 Selection 5-1 Selection (Decision) The second control logic structure is selection: Selection Choosing between two or more alternative actions. Selection statements alter the sequential flow

### 9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

9 Control Statements 9.1 Introduction The normal flow of execution in a high level language is sequential, i.e., each statement is executed in the order of its appearance in the program. However, depending

### 7 Introduction to C++

7 Introduction to C++ 7.1 Introduction C++ is an extension to C Programming language. It was developed at AT&T Bell Laboratories in the early 1980s by Bjarne Stroustrup. It is a deviation from traditional

### Adjusted/Modified by Nicole Tobias. Chapter 2: Basic Elements of C++

Adjusted/Modified by Nicole Tobias Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types

### Selection Statements

Chapter 5 Selection Statements 1 Statements So far, we ve used return statements and expression ess statements. e ts. Most of C s remaining statements fall into three categories: Selection statements:

### CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 18: Intermediate Code 29 Feb 08

CS412/CS413 Introduction to Compilers Tim Teitelbaum Lecture 18: Intermediate Code 29 Feb 08 CS 412/413 Spring 2008 Introduction to Compilers 1 Summary: Semantic Analysis Check errors not detected by lexical

### Variables and constants linked with operators. Uses relational and logical operators Evaluates to 1 or 0 (true or false) only

Expressions 1 Expressions Variables and constants linked with operators Arithmetic expressions Uses arithmetic operators Can evaluate to any value Logical expressions Uses relational and logical operators

### Primitive Data Types Summer 2010 Margaret Reid-Miller

Primitive Data Types 15-110 Summer 2010 Margaret Reid-Miller Data Types Data stored in memory is a string of bits (0 or 1). What does 1000010 mean? 66? 'B'? 9.2E-44? How the computer interprets the string

### Java Interview Questions and Answers

1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write and compile the java

### COMP 356 Programming Language Structures Notes for Chapter 5 of Concepts of Programming Languages Names, Types and Scopes

Some definitions: COMP 356 Programming Language Structures Notes for Chapter 5 of Concepts of Programming Languages Names, Types and Scopes a name is a string of characters (a word) that represents a program

### A First Book of C++ Chapter 2 Data Types, Declarations, and Displays

A First Book of C++ Chapter 2 Data Types, Declarations, and Displays Objectives In this chapter, you will learn about: Data Types Arithmetic Operators Variables and Declarations Common Programming Errors

### GETTING STARTED WITH C++ C++ BASICS - 1 -

- 1 - GETTING STARTED WITH C++ Programming is a core activity in the process of performing tasks or solving problems with the aid of a computer. An idealised picture is: PROBLEM COMPUTER SOLUTION Unfortunately

### 6.087 Lecture 3 January 13, 2010

6.087 Lecture 3 January 13, 2010 Review Blocks and Compound Statements Control Flow Conditional Statements Loops Functions Modular Programming Variable Scope Static Variables Register Variables 1 Review:

### Basic C Operators. Arithmetic operators. Assignment operators Equalities and relational operators Logical operators Conditional operator

Basic C Operators Arithmetic operators Unary operators Binary operators Assignment operators Equalities and relational operators Logical operators Conditional operator 1 Arithmetic Operators I In C, we

### Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

JAVA OPERATORS GENERAL Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: Arithmetic Operators Relational Operators Bitwise Operators

### Course: Introduction to Java Using Eclipse Training

Course: Introduction to Java Using Eclipse Training Course Length: Duration: 5 days Course Code: WA1278 DESCRIPTION: This course introduces the Java programming language and how to develop Java applications

### A relational operator is used to make comparison between two expressions. All these operators are binary and require two operands.

Control Structures in C++ Index Control Structures in C++ 3.1 Relational Operators A relational operator is used to make comparison between two expressions. All these operators are binary and require two

### Chapter 2: Problem Solving Using C++

Chapter 2: Problem Solving Using C++ 1 Objectives In this chapter, you will learn about: Modular programs Programming style Data types Arithmetic operations Variables and declaration statements Common

### UNIT-1. C Programming & Data Structures. Introduction to Computers: Computing Environment: Types of Computing Environments:

Introduction to Computers: C Programming & Data Structures UNIT-1 A computer system consists of hardware and software. Computer hardware is the collection of physical elements that comprise a computer

### Today s topics. Java programs. Java Virtual Machine (JVM) Bytecodes. HelloWorld.java javac HelloWorld.class

Today s topics Java programs Parsing Java Programming Notes from Tammy Bailey Reading Great Ideas, Chapter 3 & 4 Java programs are created as text files using a text editor (like emacs) Save to disk with.java

### Going from Python to C

Going from Python to C Darin Brezeale December 8, 2011 Python is a high-level, interpreted language. C has many of the same types of programming constructs as in Python: arrays, loops, conditionals, functions,

### Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Handout 1 CS603 Object-Oriented Programming Fall 15 Page 1 of 11 Handout 1 Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Java

### Introduction to C Programming

Introduction to C Programming C HOW TO PROGRAM, 6/E 1992-2010 by Pearson Education, Inc. All Rights Reserved. 2.1 Introduction The C language facilitates a structured and disciplined approach to computer

### Review questions for Chapter 9

Answer first, then check at the end. Review questions for Chapter 9 True/False 1. A compiler translates a high-level language program into the corresponding program in machine code. 2. An interpreter is

### What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

What is a Loop? CSC Intermediate Programming Looping A loop is a repetition control structure It causes a single statement or a group of statements to be executed repeatedly It uses a condition to control

### The IC Language Specification. Spring 2006 Cornell University

The IC Language Specification Spring 2006 Cornell University The IC language is a simple object-oriented language that we will use in the CS413 project. The goal is to build a complete optimizing compiler

### PL / SQL Basics. Chapter 3

PL / SQL Basics Chapter 3 PL / SQL Basics PL / SQL block Lexical units Variable declarations PL / SQL types Expressions and operators PL / SQL control structures PL / SQL style guide 2 PL / SQL Block Basic

### The C Programming Language course syllabus associate level

TECHNOLOGIES The C Programming Language course syllabus associate level Course description The course fully covers the basics of programming in the C programming language and demonstrates fundamental programming

### C Programming Dr. Hasan Demirel

C How to Program, H. M. Deitel and P. J. Deitel, Prentice Hall, 5 th edition (3 rd edition or above is also OK). Introduction to C Programming Dr. Hasan Demirel Programming Languages There are three types

### Chapter 2. Values, Variables, and Types. 2.1 Java Values in DrJava s Interaction Pane

14 Chapter 2 Values, Variables, and Types In this chapter we explore the primitive building blocks that are used to develop Java programs. We experiment with the following concepts within DrJava s interactive

### ESCI 386 IDL Programming for Advanced Earth Science Applications Lesson 6 Program Control

ESCI 386 IDL Programming for Advanced Earth Science Applications Lesson 6 Program Control Reading: Bowman, Chapters 16 CODE BLOCKS A code block consists of several lines of code contained between a BEGIN

### Database Programming with PL/SQL: Learning Objectives

Database Programming with PL/SQL: Learning Objectives This course covers PL/SQL, a procedural language extension to SQL. Through an innovative project-based approach, students learn procedural logic constructs

### AP Computer Science Java Subset

APPENDIX A AP Computer Science Java Subset The AP Java subset is intended to outline the features of Java that may appear on the AP Computer Science A Exam. The AP Java subset is NOT intended as an overall

### CS201- Introduction to Programming Latest Solved Mcqs from Final term Papers July 11,2011

CS201- Introduction to Programming Latest Solved Mcqs from Final term Papers July 11,2011 Mc100401285 moaaz.pk@gmail.com Moaaz Siddiq Bc100400662 bc100400662asad@gmail.com Asad Ali Latest Mcqs FINALTERM

### BHARATHIAR UNIVERSITY: COIMBATORE CENTRE FOR COLLABORATION OF INDUSTRY AND INSTITUTIONS(CCII) CERTIFICATE IN ADVANCED PROGRAMMING C++ LANGUAGE

Certificate in Advanced Programming - C++ Language Page 1 of 7 BHARATHIAR UNIVERSITY: COIMBATORE 641046 CENTRE FOR COLLABORATION OF INDUSTRY AND INSTITUTIONS(CCII) CERTIFICATE IN ADVANCED PROGRAMMING C++

### Outline. Conditional Statements. Logical Data in C. Logical Expressions. Relational Examples. Relational Operators

Conditional Statements For computer to make decisions, must be able to test CONDITIONS IF it is raining THEN I will not go outside IF Count is not zero THEN the Average is Sum divided by Count Conditions

### 2 Programs: Instructions in the Computer

2 2 Programs: Instructions in the Computer Figure 2. illustrates the first few processing steps taken as a simple CPU executes a program. The CPU for this example is assumed to have a program counter (PC),

### Dept. of CSE, IIT KGP

Programming in C: Basics CS10001: Programming & Data Structures Pallab Dasgupta Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur Types of variable We must declare the

### Repetition and Loops. Additional Python constructs that allow us to effect the (1) order and (2) number of times that program statements are executed.

New Topic Repetition and Loops Additional Python constructs that allow us to effect the (1) order and (2) number of times that program statements are executed. These constructs are the 1. while loop and

### Number Systems and. Data Representation

Number Systems and Data Representation 1 Lecture Outline Number Systems Binary, Octal, Hexadecimal Representation of characters using codes Representation of Numbers Integer, Floating Point, Binary Coded

### 1. A(n) structure is a logical design that controls the order in which a set of statements execute. a. function b. control c. sequence d.

Chapter Four MULTIPLE CHOICE 1. A(n) structure is a logical design that controls the order in which a set of statements execute. a. function b. control c. sequence d. iteration 2. The decision structure

### Writing Control Structures

Writing Control Structures Copyright 2006, Oracle. All rights reserved. Oracle Database 10g: PL/SQL Fundamentals 5-1 Objectives After completing this lesson, you should be able to do the following: Identify

### 1 Description of The Simpletron

Simulating The Simpletron Computer 50 points 1 Description of The Simpletron In this assignment you will write a program to simulate a fictional computer that we will call the Simpletron. As its name implies

### Computers process data under the control of sets of instructions called computer programs.

Introduction Computer is a device capable of performing computations and making logical decisions at speeds millions and even billions of times faster than human beings. Computers process data under the

### Informatica e Sistemi in Tempo Reale

Informatica e Sistemi in Tempo Reale Introduction to C programming Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 25, 2010 G. Lipari (Scuola Superiore Sant Anna)

### High-Level Programming Languages. Nell Dale & John Lewis (adaptation by Michael Goldwasser)

High-Level Programming Languages Nell Dale & John Lewis (adaptation by Michael Goldwasser) Low-Level Languages What are disadvantages of low-level languages? (e.g., machine code or assembly code) Programming

### Chapter 1. 1.1Reasons for Studying Concepts of Programming Languages

Chapter 1 1.1Reasons for Studying Concepts of Programming Languages a) Increased ability to express ideas. It is widely believed that the depth at which we think is influenced by the expressive power of

### High level language programs versus Machine code

High level language programs versus Machine code You all have experience programming in a high level language. You know that when you write a program in a language such as C or Java, the program is nothing

### Sources: On the Web: Slides will be available on:

C programming Introduction The basics of algorithms Structure of a C code, compilation step Constant, variable type, variable scope Expression and operators: assignment, arithmetic operators, comparison,

### Final Exam Review. CS 1428 Fall Jill Seaman. Final Exam

Final Exam Review CS 1428 Fall 2011 Jill Seaman 1 Final Exam Friday, December 9, 11:00am to 1:30pm Derr 241 (here) Closed book, closed notes, clean desk Comprehensive (covers entire course) 25% of your

### Which of the following is the correct operator to compare two variables? A. := B. = C. equal D. ==

Group 1 Question 1. What is the correct value to return to the operating system upon the successful completion of a program? A. -1 B. 1 C. 0 D. Programs do not return a value. Question 2. What is the only

### Programming for MSc Part I

Herbert Martin Dietze University of Buckingham herbert@the-little-red-haired-girl.org July 24, 2001 Abstract The course introduces the C programming language and fundamental software development techniques.

### INDEX. C programming Page 1 of 10. 5) Function. 1) Introduction to C Programming

INDEX 1) Introduction to C Programming a. What is C? b. Getting started with C 2) Data Types, Variables, Constants a. Constants, Variables and Keywords b. Types of Variables c. C Keyword d. Types of C

### Adjusted/Modified by Nicole Tobias. Chapter 5: Control Structures II (Repetition)

Adjusted/Modified by Nicole Tobias Chapter 5: Control Structures II (Repetition) Objectives In this chapter, you will: Learn about repetition (looping) control structures Explore how to construct and use

### C Control Statements : Branching and jumps

C Control Statements : Branching and jumps Using Bloodshed Dev-C++ Heejin Park Hanyang University 2 Introduction The if Statement Adding else to the if Statement Let's Get Logical A Word-Count Program

### CSC 7101: Programming Language Structures 1

Types in Programming Languages Stansifer Ch. 4 Cardelli Sec. 1 1 Types Organization of untyped values Untyped universes: bit strings, S-expr, Categorize based on usage and behavior Type = set of computational

### Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

### 05 Case Study: C Programming Language

CS 2SC3 and SE 2S03 Fall 2009 05 Case Study: C Programming Language William M. Farmer Department of Computing and Software McMaster University 18 November 2009 The C Programming Language Developed by Dennis

### Flow of Control. Conditional Statements. Boolean Expressions. CMPT 125: Lecture 4 Conditionals and Loops

Flow of Control CMPT 125: Lecture 4 Conditionals and Loops Tamara Smyth, tamaras@cs.sfu.ca School of Computing Science, Simon Fraser University January 17, 2009 The order in which statements are executed

### Primitives and Arithmetic

CS106A, Stanford Handout #29 Fall, 2004-05 Nick Parlante Primitives and Arithmetic Objects vs. Primitives Types in Java are divided into two camps: objects and primitives. Objects are relatively complex