More Programming Constructs -- Introduction

Similar documents
CHAPTER 3 Expressions, Functions, Output

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

Operators. Java operators are classified into three categories:

Chapter 3: Operators, Expressions and Type Conversion

ECE 122 Engineering Problem Solving with Java

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

COMP Primitive and Class Types. Yi Hong May 14, 2015

CS313D: ADVANCED PROGRAMMING LANGUAGE

Conditionals and Loops

Operators in java Operator operands.

Programming for Engineers Iteration

Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1

Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition

Operators in C. Staff Incharge: S.Sasirekha

JAVA OPERATORS GENERAL

Chapter 4. Operations on Data

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

Program Development. Java Program Statements. Design. Requirements. Testing. Implementation

Data Conversion & Scanner Class

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and

The Arithmetic Operators

Chapter 4: Basic C Operators

Module 2: Computer Arithmetic

Zheng-Liang Lu Java Programming 45 / 79

Outline. Performing Computations. Outline (cont) Expressions in C. Some Expression Formats. Types for Operands

Operators and Expressions

A variable is a name for a location in memory A variable must be declared

Announcements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop

Operators and Expressions:

Computer System and programming in C

Chapter 3: Arithmetic for Computers

Operators. Lecture 3 COP 3014 Spring January 16, 2018

AYBUKE BUYUKCAYLI KORAY OZUYAR MUSTAFA SOYLU. Week 21/02/ /02/2007 Lecture Notes: ASCII

UNIT- 3 Introduction to C++

Chapter 6 Primitive types

Program Development. Chapter 3: Program Statements. Program Statements. Requirements. Java Software Solutions for AP* Computer Science A 2nd Edition

Chapter 3: Program Statements

Java enum, casts, and others (Select portions of Chapters 4 & 5)

LECTURE 3 C++ Basics Part 2

Lecture 3 Tao Wang 1

Declaration and Memory

4 Operations On Data 4.1. Foundations of Computer Science Cengage Learning

Operators and Expressions in C & C++ Mahesh Jangid Assistant Professor Manipal University, Jaipur

CMPT 125: Lecture 3 Data and Expressions

Computational Expression

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

Java Notes. 10th ICSE. Saravanan Ganesh

Expressions & Assignment Statements

Programming in C++ 5. Integral data types

Introduction. Following are the types of operators: Unary requires a single operand Binary requires two operands Ternary requires three operands

Chapter 7. Expressions and Assignment Statements ISBN

These are reserved words of the C language. For example int, float, if, else, for, while etc.

Basics of Java Programming

3. Java - Language Constructs I

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003

A Java program contains at least one class definition.

ISA 563 : Fundamentals of Systems Programming

Engineering Computing I

Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators

Full file at

Operators. Java Primer Operators-1 Scott MacKenzie = 2. (b) (a)

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Prof. Navrati Saxena TA: Rochak Sachan

Chapter 2: Data and Expressions

Number Systems Standard positional representation of numbers: An unsigned number with whole and fraction portions is represented as:

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Le L c e t c ur u e e 2 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Variables Operators

3. EXPRESSIONS. It is a sequence of operands and operators that reduce to a single value.

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9

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

Introduction to Computers and Programming. Numeric Values

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

Unit 3. Operators. School of Science and Technology INTRODUCTION

BRANCHING if-else statements

Comparing Data. Comparing Floating Point Values. Comparing Float Values. CS257 Computer Science I Kevin Sahr, PhD

Sir Muhammad Naveed. Arslan Ahmed Shaad ( ) Muhammad Bilal ( )

Types and Expressions. Chapter 3

A complex expression to evaluate we need to reduce it to a series of simple expressions. E.g * 7 =>2+ 35 => 37. E.g.

Chapter 3. Selections

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

Chapter 03: Computer Arithmetic. Lesson 09: Arithmetic using floating point numbers

Chapter 7. Expressions and Assignment Statements

Chapter 7. Expressions and Assignment Statements (updated edition 11) ISBN

Week 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.

CS1004: Intro to CS in Java, Spring 2005

Chapter 2. Elementary Programming

Fundamental of Programming (C)

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

CT 229 Java Syntax Continued

In Fig. 3.5 and Fig. 3.7, we include some completely blank lines in the pseudocode for readability. programs into their various phases.

Chapter 2: Data and Expressions

Operations On Data CHAPTER 4. (Solutions to Odd-Numbered Problems) Review Questions

Unit-II Programming and Problem Solving (BE1/4 CSE-2)

C/C++ Programming for Engineers: Working with Integer Variables

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Declaration. Fundamental Data Types. Modifying the Basic Types. Basic Data Types. All variables must be declared before being used.

Visual C# Instructor s Manual Table of Contents

Transcription:

More Programming Constructs -- Introduction We can now examine some additional programming concepts and constructs Chapter 5 focuses on: internal data representation conversions between one data type and another more operators more selection statements more repetition statements 1

Internal Data Representation We discussed earlier that every piece of information stored on a computer is represented as binary values What is represented by the following binary string? 01100001001010 You can't tell just from the bit string itself. We take specific binary values and apply an interpretation to them 2

Representing Integers There are four types of integers in Java, each providing a different bits to store the value Each has a sign bit. If it is 1, the number is negative; if it is 0, the number is positive byte s 7 bits short s 15 bits int s 31 bits long s 63 bits 3

Two's Complement Integers are stored in signed two's complement format A positive value is a straightforward binary number A negative value is represented by inverting all of the bits of the corresponding positive value, then adding 1 To "decode" a negative value, invert all of the bits and add 1 Using two's complement makes internal arithmetic processing easier 4

Two's Complement The number 25 is represented in 8 bits (byte) as 00011001 To represent -25, first invert all of the bits 11100110 then add 1 11100111 Note that the sign bit reversed, indicating the number is negative 5

Overflow and Underflow Storing numeric values in a fixed storage size can lead to overflow and underflow problems Overflow occurs when a number grows too large to fit in its allocated space Underflow occurs when a number shrinks too small to fit in its allocated space See Overflow.java 6

Representing Floating Point Values A decimal (base 10) floating point value can be defined by the following equation sign * mantissa * 10 exponent where sign is either 1 or -1 mantissa is a positive value that represents the significant digits of the number exponent is a value that indicates how the decimal point is shifted relative to the mantissa 7

Representing Floating Point Values For example, the number -843.977 can be represented by -1 * 843977 * 10-3 Floating point numbers can be represented in binary the same way, except that the mantissa is a binary number and the base is 2 instead of 10 sign * mantissa * 2 exponent Floating point values are stored by storing each of these components in the space allotted 8

Representing Characters As described earlier, characters are represented according to the Unicode Character Set The character set matches a unique number to each character to be represented Storing the character is therefore as simple as storing the binary version of the number that represents it For example, the character 'z' has the Unicode value 122, which is represented in 16 bits as 0000000001111010 9

Representing Characters Because they are stored as numbers, Java lets you perform some arithmetic processing on characters For example, because 'A' is stored as Unicode value 65, the statement char ch = 'A' + 5; will store the character 'F' in ch (Unicode value 70) This relationship is occasionally helpful 10

Conversions Each data value and variable is associated with a particular data type It is sometimes necessary to convert a value of one data type to another Not all conversions are possible. For example, boolean values cannot be converted to any other type and vice versa Even if a conversion is possible, we need to be careful that information is not lost in the process 11

Widening Conversions Widening conversions are generally safe because they go from a smaller data space to a larger one The widening conversions are: From To byte short char int long float short, int, long, float, or double int, long, float, or double int, long, float, or double long, float, or double float or double double 12

Narrowing Conversions Narrowing conversions are more dangerous because they usually go from a smaller data space to a larger one The narrowing conversions are: From To byte short char int long float double char byte or char byte or short byte, short, or char byte, short, char, or int byte, short, char, int or long byte, short, char, int, long, or float 13

Performing Conversions In Java, conversion between one data type and another can occur three ways Assignment conversion - when a value of one type is assigned to a variable of another type Arithmetic promotion - occurs automatically when operators modify the types of their operands Casting - an operator that forces a value to another type 14

Assignment Conversion For example, if money is a float variable and dollars is an int variable (storing 82), then money = dollars; converts the value 82 to 82.0 when it is stored The value in dollars is not actually changed Only widening conversions are permitted through assignment Assignment conversion can also take place when passing parameters (which is a form of assignment) 15

Arithmetic Promotion Certain operators require consistent types for their operands For example, if sum is a float variable and count is an int variable, then the statement result = sum / count; internally converts the value in count to a float then performs the division, producing a floating point result The value in count is not changed 16

Casting A cast is an operator that is specified by a type name in parentheses It is placed in front of the value to be converted The following example truncates the fractional part of the floating point value in money and stores the integer portion in dollars dollars = (int) money; The value in money is not changed If a conversion is possible, it can be done through a cast 17

More Operators We've seen several operators of various types: arithmetic, equality, relational There are many more in Java to make use of: increment and decrement operators logical operators assignement operators the conditional operator 18

The Increment and Decrement Operators The increment operator (++) adds one to its integer or floating point operand The decrement operator (--) subtracts one The statement count++; is essentially equivalent to count = count + 1; 19

The Increment and Decrement Operators The increment and decrement operators can be applied in prefix (before the variable) or postfix (after the variable) form When used alone in a statement, the prefix and postfix forms are basically equivalent. That is, count++; is equivalent to ++count; 20

The Increment and Decrement Operators When used in a larger expression, the prefix and postfix forms have a different effect In both cases the variable is incremented (decremented) But the value used in the larger expression depends on the form Expression count++ ++count count-- --count Operation add 1 add 1 subtract 1 subtract 1 Value of Expression old value new value old value new value 21

The Increment and Decrement Operators If count currently contains 45, then total = count++; assigns 45 to total and 46 to count If count currently contains 45, then total = ++count; assigns the value 46 to both total and count 22

The Increment and Decrement Operators If sum contains 25, then the statement System.out.println (sum++ + " " + ++sum + " " + sum + " " + sum--); prints the following result: 25 27 27 27 and sum contains 26 after the line is complete 23

Logical Operators There are three logical operators in Java: Operator! && Operation Logical NOT Logical AND Logical OR They all take boolean operands and produce boolean results Logical NOT is unary (one operand), but logical AND and OR are binary (two operands) 24

Logical NOT The logical NOT is also called logical negation or logical complement If a is true,!a is ; if a is, then!a is true Logical expressions can be shown using truth tables a!a true true 25

Logical AND The expression a && b is true if both a and b are true, and otherwise Truth tables show all possible combinations of all terms a b a && b true true true true true 26

Logical OR The expression a b is true if a or b or both are true, and otherwise a b a b true true true true true true true 27

Logical Operators Conditions in selection statements and loops can use logical operators to form more complex expressions if (total < MAX &&!found) System.out.println ("Processing..."); Logical operators have precedence relationships between themselves and other operators 28

Logical Operators Full expressions can be evaluated using truth tables total < MAX found!found total < MAX &&!found true true true true true true true 29

Assignment Operators Often we perform an operation on a variable, then store the result back into that variable Java provides assignment operators that simplify that process For example, the statement num += count; is equivalent to num = num + count; 30

Assignment Operators There are many such assignment operators, always written as op=, such as: Operator Example Equivalent To += -= *= /= %= x += y x -= y x *= y x /= y x %= y x = x + y x = x - y x = x * y x = x / y x = x % y 31

Assignment Operators The right hand side of an assignment operator can be a complete expression The entire right-hand expression is evaluated first, then combined with the additional operation Therefore result /= (total-min) % num; is equivalent to result = result / ((total-min) % num); 32

The Conditional Operator Java has a conditional operator that evaluates a boolean condition that determines which of two expressions is evaluated The result of the chosen expression is the result of the entire conditional operator Its syntax is: condition? expression1 : expression2 If the condition is true, expression1 is evaluated; if it is, expression2 is evaluated 33

The Conditional Operator It is similar to an if-else statement, except that it is an expression that returns a value For example: larger = (num1 > num2)? num1 : num2; If num1 is greater that num2, then num1 is assigned to larger; otherwise, num2 is assigned to larger The conditional operator is ternary, meaning it requires three operands 34

The Conditional Operator Another example: System.out.println ("Your change is " + count + (count == 1)? "Dime" : "Dimes"); If count equals 1, "Dime" is printed, otherwise "Dimes" is printed 35

Another Selection Statement The if and the if-else statements are selection statements, allowing us to select which statement to perform next based on some boolean condition Another selection construct, called the switch statement, provides another way to choose the next action The switch statement evaluates an expression, then attempts to match the result to one of a series of values Execution transfers to statement list associated with the first value that matches 36

The switch Statement The syntax of the switch statement is: switch (expression) { case value1: statement-list1 case value2: statement-list2 case } 37

The switch Statement The expression must evaluate to an integral value, such as an integer or character The break statement is usually used to terminate the statement list of each case, which causes control to jump to the end of the switch statement and continue A default case can be added to the end of the list of cases, and will execute if no other case matches See Vowels.java 38

More Repetition Constructs In addition to while loops, Java has two other constructs used to perform repetition: the do statement the for statement Each loop type has its own unique characteristics You must choose which loop type to use in each situation 39

The do Statement The do statement has the following syntax: do statement while (condition); The statement is executed until the condition becomes It is similar to a while statement, except that its termination condition is evaluated after the loop body 40

The do Statement statement true condition 41

The do Statement See Dice.java The key difference between a do loop and a while loop is that the body of the do loop will execute at least once If the condition of a while loop is initially, the body of the loop is never executed Another way to put this is that a while loop will execute zero or more times and a do loop will execute one or more times 42

The for Statement The syntax of the for loop is for (intialization; condition; increment) statement; which is equivalent to initialization; while (condition) { statement; increment; } 43

The for Statement Like a while loop, the condition of a for statement is tested prior to executing the loop body Therefore, a for loop will execute zero or more times It is well suited for executing a specific number of times, known in advance Note that the initialization portion is only performed once, but the increment portion is executed after each iteration 44

The for Statement initialization condition true statement increment 45

The for Statement Examples: for (int count=1; count < 75; count++) System.out.println (count); for (int num=5; num <= total; num *= 2) { sum += num; System.out.println (sum); } See Dice2.java 46

The for Statement Each expression in the header of a for loop is optional If the initialization is left out, no initialization is performed If the condition is left out, it is always considered to be true, and therefore makes an infinite loop If the increment is left out, no increment opertion is performed Both semi-colons are always required 47

The break and continue statements The break statement, which we used with switch statements, can also be used inside a loop When the break statement is executed, control jumps to the statement after the loop (the condition is not evaluated again) A similar construct, the continue statement, can also be executed in a loop When the continue statement is executed, control jumps to the end of the loop and the condition is evaluated 48

The break and continue Statements They can calso be used to jump to a line in your program with a particular label Jumping from one point in the program to another in an unstructured manner is not good practice Therefore, as a rule of thumb, avoid the break statement except when needed in switch statements, and avoid the continue statement altogether 49