ITM 352 Expressions, Precedence, Working with Strings Class #5

Slides:



Advertisements
Similar presentations
Aalborg Media Lab 21-Jun-15 Software Design Lecture 2 “ Data and Expressions”
Advertisements

Program Elements We can now examine the core elements of programming (as implemented in Java) We focuse on: data types variable declaration and use, constants.
Expressions An expression is a sequence of operands and operators that reduces to a single value expression operator operand An operator is a language-specific.
1 Chapter 2: Elementary Programming Shahriar Hossain.
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
Performing Computations C provides operators that can be applied to calculate expressions: example: tax is 8.5% of the total sale expression: tax =
Basic Elements of C++ Chapter 2.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
CHAPTER:8 OPERATORS AND EXPRESSION IN C++ Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्सजेंड़र ) PGT(CS),KV JHAGRAKHAND.
Chapter 2 part #4 Operator
2440: 211 Interactive Web Programming Expressions & Operators.
Chapter 3: Data Types and Operators JavaScript - Introductory.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
LESSON 6 – Arithmetic Operators
CHAPTER 2 PART #4 OPERATOR 2 nd semester King Saud University College of Applied studies and Community Service Csc 1101 By: Asma Alosaimi Edited.
Chapter 2Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 2 l Primitive Data types l Strings: a class l Assignment l.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
ITM © Port, KazmanVariables - 1 ITM 352 Expressions, Precedence, Working with Strings.
Chapter 2Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 2 l Primitive Data types l Strings: a class l Assignment l.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
COMP Primitive and Class Types Yi Hong May 14, 2015.
Operators and Expressions. 2 String Concatenation  The plus operator (+) is also used for arithmetic addition  The function that the + operator performs.
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
1 Week 5 l Primitive Data types l Assignment l Expressions l Documentation & Style Primitive Types, Assignments, and Expressions.
Computer Programming with Java Chapter 2 Primitive Types, Assignment, and Expressions.
1 CSC 221: Computer Programming I Fall 2005 simple conditionals and expressions  if statements, if-else  increment/decrement, arithmetic assignments.
Literals A literal (sometimes called a constant) is a symbol which evaluates to itself, i.e., it is what it appears to be. Examples: 5 int literal
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Expressions Version Topics Arithmetic expressions Conversions Operator precedence String class 2.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
Java Programming: Guided Learning with Early Objects Chapter 1 Basic Elements of Java.
Chapter Topics The Basics of a C++ Program Data Types
Chapter 6 JavaScript: Introduction to Scripting
Lecture 3 Java Operators.
Building Java Programs
Basic Elements of C++.
Revision Lecture
Multiple variables can be created in one declaration
Assignment and Arithmetic expressions
Primitive Data, Variables, Loops (Maybe)
Type Conversion, Constants, and the String Object
Intro to PHP & Variables
Java Programming: From Problem Analysis to Program Design, 4e
Basic Elements of C++ Chapter 2.
Operators and Expressions
Lecture 3 Expressions Richard Gesick.
Numerical Data Types.
Building Java Programs
Chapter-3 Operators.
Building Java Programs Chapter 2
Web Programming– UFCFB PHP Basics Lecture 18
Expressions and Assignment
elementary programming
Assignment Operators Topics Increment and Decrement Operators
Chapter 2: Introduction to C++.
Data Types and Expressions
Building Java Programs
Primitive Types, Strings, and Console I/O
Comments Any string of symbols placed between the delimiters /* and */. Can span multiple lines Can’t be nested! Be careful. /* /* /* Hi */ is an example.
Building Java Programs
In this class, we will cover:
Primitive Types and Expressions
Building Java Programs Chapter 2
Assignment Operators Topics Increment and Decrement Operators
Operator King Saud University
Building Java Programs
Expressions An Expression is a sequence of operands and operators that reduces to a single value. An operator is a language-specific syntactical token.
Data Types and Expressions
Assignment Operators Topics Increment and Decrement Operators
Data Types and Expressions
Presentation transcript:

ITM 352 Expressions, Precedence, Working with Strings Class #5

Review: What is a PHP File? PHP files have extension ".php” A PHP file can contain text, CSS, HTML and, of course, PHP code. PHP code is executed on the server, and the result is returned to the browser as plain HTML.

Review: What is a PHP Program? A PHP program starts with <?php and ends with ?> In between is a series of statements in the PHP language. Anything else, before or after, is interpreted as HTML!!!!

Review: What is a PHP Statement? A PHP programs normally contain comments and code (statements) Comments: start with // or # or begin with /* and end with */ Statements end with a ; Let’s take a look at the most common types of statements…

Expressions Expressions are PHP statements that return values and use operators the value produced by an expression when evaluated is "returned", i.e. it is the statement's "return value." $numberOfBaskets = 5; // assignment returns 5 $eggsPerBasket = 8; $totalEggs = $numberOfBaskets * $eggsPerBasket; In the first two lines when the assignment operation is evaluated the expression returns the value 5 for the first line and 8 for the second $numberOfBaskets * $eggsPerBasket is an expression that returns the integer value 40 $check = ($totalEggs = $numberOfBaskets * $eggsPerBasket) / 40; Similarly, functions return values (more on this later…)

Operators Operators take operands and perform some operation There are unary, binary, and tertiary operators that use 1, 2, and 3 operands respectively. Examples: Unary: $endOfFile++, !is_string() Binary: 2 * 3, $a % 3, $a = 40, $a > 3, $a == 5, $a || $b Usually arithmetic, but can be other operations See next slide for example…

Simple Expressions PHP will interpret operations between different data types according to certain casting rules and precedence $whatIsThis = 1.2 + " Fred" . 0777 * true; Our goal is to understand why the value of the above expression is 1.2511 (after the next bunch of slides). The same variable can appear on both sides of the assignment operator $a = $a + 1; // add 1 to value in $a and set in $a This is unlike algebra and actually very useful!

Operators and Precedence (Partial) Associativity Operators non-associative ++ -- (int) (float) (string) (array) (object) (bool) right ! left * / % + - . < <= > >= <> == != === !== && ||

Operator Precedence and Parentheses Expressions follow certain rules that determine the order an expression is evaluated e.g. should 2 + 3 * 4 be 5*4 or 2+12? PHP operators have precedence similar to algebra to deal with this Operators with higher preference are evaluated first Ex. In the expression 2 + 3*4, the * operator has higher precedence than + so 3*4 is evaluated first to return the value 12, then the expression 2 + 12 is evaluated to return 14 Use parentheses '( )' to force evaluation for lower precedence Ex. (2 + 3)*4 Do not clutter expressions with parentheses when the precedence is correct and obvious!

Precedence An example of precedence rules to illustrate which operators in the following expression should be evaluated first: $score < $min/2 – 10 || $score > 90 Division operator has highest precedence of all operators used here so we show it as if it were parenthesized: $score < ($min/2) – 10 || $score > 90 Subtraction operator has next highest precedence : $score < (($min/2) – 10) || $score > 90 The < and > operators have equal precedence and are evaluated left-to-right: ($score < (($min/2) – 10)) || ($score > 90) This is a fully parenthesized expression that is equivalent to the original. It shows the order in which the operators in the original will be evaluated.

Operator Associativity Some operators have the same precedence order. Ex. Is 4 / 2 *3 first evaluated 4 / 6 or 2 * 3 ? In such cases, the associativity determines the order of evaluation The / and * operators are left-associative and so the operations are performed from left to right 4 / 2 is first, returning 2, then 2 * 3 returning 6

Examples of Arithmetic Precedence Do Lab Exercise #1

Casting: Changing the Data Type of the Returned Value Casting is the process of converting from one data type to another data type. This can be useful. Casting only changes the type of the returned value (the single instance where the cast is done), not the type of the variable For example: $n = 5.0; $x = (int) $n; Since $n is a float, (int) $n converts the value to an int, now $x is an integer type.

Implicit Type Casting Casting is done implicitly (automatically) when a "lower" type is assigned to a "higher" type The data type hierarchy (from lowest to highest): bool --> int --> float --> string --> array --> object For example: $x = 0; $n = 5 + 10.45; $x = $n; the value 5 is cast to a float, then assigned to $n $x now is a float This is called implicit casting because it is done automatically.

Data Types in an Expression: More Implicit Casting Some expressions have a mix of data types All values are automatically elevated (implicitly cast) to the highest level before the calculation For example: $n = 2; $x = 5.1; $y = 1.33; $a = (n * x)/y; $n is automatically cast to type float before performing the multiplication and division

Casting: Changing the Data Type of the Returned Value Casting is the process of converting from one data type to another data type. This is sometimes useful. Casting only changes the type of the returned value (the single instance where the cast is done), not the type of the variable For example: $n = 5.0; $x = (int) $n; Since $n is a float, (int) $n converts the value to an int, now $x is an integer type. ** WARNING ** Odd things can happen when casting from a higher to a lower type: $low = (int) 5.2345; // returns 5 $high = (int) 5.999; // returns 5 So why does 1.2 + " Fred" . 0777 * true evaluate to 1.2511?

Increment and Decrement Operators Shorthand notation for common arithmetic operations used for counting (up or down) The counter can be incremented (or decremented) before or after using its current value ++$count; // preincrement: $count = $count + 1 before using it $count++; // postincrement: $count = $count + 1 after using it --$count; // predecrement: $count = $count - 1 before using it $count--; // postdecrement: $count = $count - 1 after using it You can also increment and decrement non-integers $var = 'a'; $var++; // $var now 'b' What if $var = 'az' ?

Increment/Decrement Operator Examples Common code: $n = 3; $m = 4; What will be the value of m and result after each of these executes? (a) $result = $n * ++$m;//preincrement $m (b) $result = $n * $m++;//postincrement $m (c) $result = $n * --$m;//predecrement $m (d) $result = $n * $m--;//postdecrement $m Do Lab Exercise #2

Specialized Assignment Operators A shorthand notation for performing an operation on and assigning a new value to a variable General form: var <op>= expression; equivalent to: var = var <op> (expression); Where <op> is +, -, *, /, %, . , |, ^, ~, &, <<, >> Examples: $amount += 5; //same as $amount = $amount + 5; $amount *= 1 + $interestRate; //$amount = $amount * (1 + $interestRate); Note that the right side is treated as a unit Do Lab Exercise #3

Single vs. Double Quotes vs. Heredoc Three ways to declare a string value Single quotes 'So this is Christmas?'; Double quotes "How about Kwanza?"; Here Documents <<< When_Will_It_End It was a dark and stormy night, my son said, "Dad, tell me a story" so I said, "It was a dark and stormy night, my son said, "Dad, tell me a story" so I said, "It was a dark and stormy night, my son said, "Dad, tell me a story" so I said, When_Will_It_End

Strings Any sequence of characters e.g. abcd*123$!19 In PHP these are referred to as string Designated as a literal by single or double quotes 'string', "string" Note: Any variables inside a double quoted string are expanded into that string, single quoted strings are not expanded $a = 10; echo "I have $a more slides"; I have 10 more slides $a = 10; echo 'I have $a more slides'; I have $a more slides

I need more $ but they \'ed the budget Escape Sequences To use characters in strings that can't be typed or seen or are interpreted specially by php (such as $, {,},\, etc.) there are escape sequences \n newline (note: not the same as HTML <br>) \t tab \$ the $ character \\ the \ character Example: echo "I need more \$ but they \\'ed the budget\n"; I need more $ but they \'ed the budget

What's the Difference? The way you declare a string will affect how Escape codes (e.g. \n ) are recognized; variables are interpreted Single quotes are literal $variable = 10; echo 'This prints $variable\n'; This prints $variable\n All characters print as written, No escape codes are recognized except \' and \\ Double quotes expand variable values and escape characters $variable = 10; echo "This prints $variable\n"; This prints 10

Heredoc Multi-line string constants are easily created with a heredoc expression $variable = 'Here Here!'; $wind = <<< EDGE Line 1. \n Line 2. " " Line 3. ' ' Line 4. $variable EDGE; echo $wind; Variables are expanded, escape characters are recognized Note: the end of the heredoc (EDGE in this case) must be the first (and only) thing on the line. Do Lab Exercise #4

Concatenating (Appending) Strings The '.' operator is used for string concatenation (merging two strings): $name = "Mondo"; $greeting = "Hi there"; echo $greeting . $name . "Welcome!"; causes the following to display on the screen: Hi thereMondoWelcome! Note: you have to remember to include spaces (and other punctuation) if you want it to look right: echo $greeting . " " . $name . “, Welcome!"; which causes the following to display: Hi there Mondo, Welcome! Do Lab Exercise #5

Useful Tools: print_r(), var_dump() You can easily output variable types and their values with print_r(), var_dump() These functions are very useful for debugging your programs print_r() displays just the value, var_dump() displays the type and value Do Lab Exercise #6