CLIL-6-PHP-6. Arrays - part 1. So far we've looked at the basic variables types such as strings and integers, as

Size: px
Start display at page:

Download "CLIL-6-PHP-6. Arrays - part 1. So far we've looked at the basic variables types such as strings and integers, as"

Transcription

1 Arrays - part 1 Introduction So far we've looked at the basic variables types such as strings and integers, as well as a variety of functions you can use to manipulate these data types. Beyond the basic data types are arrays and objects, which take a little bit more work in order for you to take advantage of them properly. More importantly, arrays take a solid understanding of functions before you try to use them, which is why they are separated here! As mentioned, objects are covered exclusively in their own chapter - this chapter is dedicated to the topic of arrays. In order to model our surroundings in a programming environment accurately, it is important to recognise that some types of data naturally group together - colours, for example, naturally clump together into one group. Rather than having hundreds of separate variables - one for each colour - the reality is that it makes more sense to have one variable that holds a list, or array of colours. Topics covered in this chapter are: Reading arrays Manipulating arrays Multidimensional arrays (arrays of arrays) Saving arrays 1

2 First steps array array ( [mixed...]) int count ( mixed var [, int mode]) bool print_r ( mixed expression [, bool return]) void var_dump ( mixed expression [, mixed expression [, mixed...]]) mixed var_export ( mixed expression [, bool return]) PHP has built-in support for arrays of data, and there are two ways you can create an array: using the array function, or using a special operator, [ ]. Before we look at how arrays work, there are two key things you need to understand before you continue: An array is a normal PHP variable like any others, but it works like a container - you can put other variables inside it Each variable inside an array is called an element. Each element has a key and a value, which can be any other variable. Now, consider this PHP code: $myarray = array("apples", "Oranges", "Pears"); $size = count($myarray); print_r($myarray); On line one we see the most basic way to create an array, the array() function. The array() function takes a minimum of one parameter (and a maximum of as many as you want), and returns an array containing those variables. That's right - $myarray now contains all three variables. Line two contains a new function, count(), that returns the number of elements consisting in the array passed to it 2

3 as its only parameter - in the example we pass in my $myarray, then store the number of elements (three) in $size. Note: The array() function actually allows you to have a trailing comma after the last element, eg: array("apples", "Oranges", "Pears",). This is rarely used in hand-written code, but it can make generating code much easier. Line three contains another new function, print_r(). This takes just one parameter, but it outputs detailed information about a variable, such as it is type, length, and contents. In the case of arrays, print_r() iteratively outputs all elements inside the array - it is a good way to see how arrays work. Here is the output of print_r() from the above code: Array ( [0] => Apples [1] => Oranges [2] => Pears ) As you can see, there are our three variables - Apples is at index 0 in the array (signified by "[0]=>"), Oranges is at index 1 in the array, and Pears is at index 2 in the array. Note that if you are running your scripts through a web browser as opposed to from the command-line, you may find it help to put a HTML <pre> tag before your print_r() calls, as this will format them for easier reading. Using the proper array terminology defined earlier, the 0, 1, and 2 indices are the keys of each element, the "Apples", "Oranges", and "Pears" are the values of each 3

4 element, and the key and the value considered together are the elements themselves. Note that you can provide a second parameter to print_r(), which, if set to true, will make print_r() pass its output back as its return value, and not print anything out. To achieve the same output using this method, we would need to alter the script to this: $myarray = array("apples", "Oranges", "Pears"); $size = count($myarray); $output = print_r($myarray, true); print $output; You can store whatever you like as values in an array, and you can mix values also. For example: array("foo", 1, 9.995, "bar", $somevar). You can also put arrays inside arrays, but we will be getting on to that later. There is a similar function to print_r(), which is var_dump(). It does largely the same thing, but a) prints out sizes of variables, b) does not print out non-public data in objects, and c) does not have the option to pass a second parameter to return its output. For example, altering the first script to use var_dump() rather than print_r() would give the following output: array(3) { [0]=> string(6) "Apples" [1]=> string(7) "Oranges" [2]=> string(5) "Pears" 4

5 } In there you can see var_dump() has told us that the array has three values, and also prints out the lengths of each of the strings. For teaching purposes, var_dump() is better as it shows the variable sizes, however you will probably want to use print_r() in your own work. Finally, there is the function var_export(), which is similar to both var_dump() and print_r(). The key difference with var_export(), however, is that it prints out variable information in a style that can be used as PHP code. For example, if we had use var_export() instead of print_r() in the test script, it would have output the following: array ( 0 => 'Apples', 1 => 'Oranges', 2 => 'Pears', ) Note there is an extra comma after the last element, however this is ignored by PHP and you can copy and paste that information directly into your own scripts, like this: $foo = array ( 0 => 'Apples', 1 => 'Oranges', 2 => 'Pears', ); 5

6 Associative arrays As well as choosing individual values, you can also choose your keys - in the fruits code above we just specify values, but we could have specified keys along with them, like this: $myarray = array("a"=>"apples", "b"=>"oranges", "c"=>"pears"); var_dump($myarray); This time, var_dump() will output the following: array(3) { ["a"]=> string(6) "Apples" ["b"]=> string(7) "Oranges" ["c"]=> string(5) "Pears" } As expected, our 0, 1, and 2 element keys have been replaced with a, b, and c, but we could equally have used "Foo", "Bar", and "Baz", or even variables or other arrays to act as the keys. Specifying your own keys produces what is called an associative array - you associate a specific key with a specific value. Most associative arrays use strings as keys, but do not be afraid to try more advanced things out. The one exception here is floating-point numbers: these make very poor array indexes. The problem lies in the fact that PHP converts them to integers before 6

7 they are used, which essentially rounds them down. So, the following code will create an array with just one element in: $array[1.5] = "foo"; $array[1.6] = "bar"; The first line will read 1.5 as the key, round it down to 1, then store "foo" at index 1. The second line will read 1.6 as the key, also round it down to 1, then store "bar" at index 1, overwriting "foo". If you really want to use floating-point numbers as your keys, pass them in as strings, like this: $array["1.5"] = "foo"; $array["1.6"] = "foo"; var_dump($array); That should output the following: array(2) { ["1.5"]=> string(3) "foo" ["1.6"]=> string(3) "foo" } This time the floating-point numbers have not been rounded down or converted at all, because PHP is using them as strings. The same solution applies to reading values out from an associative array with floating-point keys - you must always specify the key as a string. 7

8 The two ways of iterating through arrays void list ( mixed...) array each ( array input) If you do not specify a key, as in the first example, PHP will just assign incrementing numbers starting with 0. However, these numbers cannot be guaranteed to exist within the array in any given order, or even to exist at all - they are just key values themselves. For example, an array may have keys 0, 1, 2, 5, 3, 6, 7. That is, it can have its keys out of order or entirely missing. As a result, code like this should generally be avoided: for ($i = 0; $i < count($array); ++$i) { print $array[$i]; } However, there is a quick and easy way to accomplish the same thing: a foreach loop, which itself has two versions. The easiest way to use foreach looks like this: foreach($array as $val) { print $val; } Here the array $array is looped through and its values are extracted into $val. In this situation, the array keys are ignored completely, which usually makes most sense when they have been auto-generated (i.e. 0, 1, 2, 3, etc). The second way to use foreach does allow you to extract keys, and looks like this: foreach ($array as $key => $val) { print "$key = $val\n"; } 8

9 Another commonly used way to loop over arrays is using the list() and each() functions, like this: while (list($var, $val) = each($array)) { print "$var is $val\n"; } List() is a function that does the opposite of array() - it takes an array, and converts it into individual variables. Each() takes an array as its parameter, and returns the current key and value in that array before advancing the array cursor. "Array cursor" is the technical term for the element of an array that is currently being read. All arrays have a cursor, and you can freely move it around - it is used in the while loop above, where we need to iterate through an array. To start with, each() will return the first element, then the second element, then the third, and so on, until it finds there are no elements left, in which case it will return false and end the loop. The meaning of that first line is "get the current element in the array, and assign its key to $var and its value to $val, then advance the array cursor. There is a lot more detail on array cursors later. Generally speaking, using foreach loops is the most optimised way to loop through an array, and is also the easiest to read. In practice, however, you will find foreach loops and list()/each() loops in about equal proportions, despite the latter option being slower. The key difference between the two is that foreach automatically starts at the front of the array, whereas list()/each() does not. 9

10 The array operator There is another popular way to create and manage arrays, and it uses brackets [ ] to mean "add to array", earning it the name "the array operator". Using this functionality, you can both create arrays and add to existing arrays, so this is generally more popular - you will generally only find the array() function being used when several values are being put inside the array, as it will fit on one line. Here are some examples of the array operator in action: $array[] = "Foo"; $array[] = "Bar"; $array[] = "Baz"; var_dump($array); That should work in precisely the same as using the array() function, except it is much more flexible - we can add to the array whenever we want to. When it comes to working with non-default indices, we can just place our key inside the brackets, like this: $array["a"] = "Foo"; $array["b"] = "Bar"; $array["c"] = "Baz"; var_dump($array); 10

11 Returning arrays from functions In PHP you can return one and only one value from your user functions, but you are able to make that single value an array, thereby allowing you to return many values. This following code shows how easy it is: function dofoo() { $array["a"] = "Foo"; $array["b"] = "Bar"; $array["c"] = "Baz"; return $array; } $foo = dofoo(); Without returning an array, the only other way to pass data back to the calling script is by accepting parameters by reference and changing them inside the function. Passing arrays by reference like this is generally preferred as it is less of a hack, and also frees up your return value for some a true/false to check whether the function was successful. 11

12 Array-specific functions Although arrays are great by themselves, their real usefulness only comes out when you use special array functions to manipulate your data - this was why we had to cover functions before arrays. There are quite a few array functions all doing a variety of things, and you need not learn them all - your best bet is to give them all a try so that you at least know how they work, then get back to working on normal code. You'll soon learn what works for you best! 12

13 Chopping and changing arrays array array_diff ( array array1, array array2 [, array...]) array array_intersect ( array array1, array array2 [, array...]) array array_merge ( array array1, array array2 [, array...]) There are three key functions that handle the comparison of two arrays to create a new array, and they work in much the same way - they take a minimum of two arrays as parameters (we will call them $arr1 and $arr2), and return an array for a result. The difference is that array_diff() returns a new array containing all the values of $arr1 that do not exist in $arr2, array_intersect() returns a new array containing all the values of $arr1 that do exist in $arr2, and array_merge() just combines the two arrays. These three functions work well as a team, and allow you to construct combined arrays out of individual arrays. Here is an example with these three functions in action: $toppings1 = array("pepperoni", "Cheese", "Anchovies", "Tomatoes"); $toppings2 = array("ham", "Cheese", "Peppers"); $inttoppings = array_intersect($toppings1, $toppings2); $difftoppings = array_diff($toppings1, $toppings2); $bothtoppings = array_merge($toppings1, $toppings2); var_dump($inttoppings); var_dump($difftoppings); var_dump($bothtoppings); As you can see, there are two arrays of pizza toppings, and they both share cheese as a value. Here is what that script outputs: array(1) { [1]=> string(6) "Cheese" } 13

14 array(3) { [0]=> string(9) "Pepperoni" [2]=> string(9) "Anchovies" [3]=> string(8) "Tomatoes" } array(7) { [0]=> string(9) "Pepperoni" [1]=> string(6) "Cheese" [2]=> string(9) "Anchovies" [3]=> string(8) "Tomatoes" [4]=> string(3) "Ham" [5]=> string(6) "Cheese" [6]=> string(7) "Peppers" } Array_intersect(), if you recall, returns an array listing all values in array parameter one that are also in array parameter two, so this call in our example will put just one element, cheese, into $inttoppings. The call to array_diff() will place into $difftoppings all the values from $toppings1 that aren't in $toppings2, namely pepperoni, anchovies, and tomatoes. Finally we have a call to array_merge(), which results in seven elements being placed into $bothtoppings: pepperoni, cheese, anchovies, tomatoes, peppers, ham, and cheese. As you can see, "cheese" is in there twice, so what you really need now is a way to strip out duplicate values. Note: The + operator in PHP is overloaded so that you can use it to merge arrays, eg $array3 = $array1 + $array2, but will ignore any key clashes, and so is quite confusing to use unless you have unique keys. 14

15 Stripping out duplicate values array array_unique ( array input) Consider if the $toppings2 array had been declared like this: $toppings2 = array("peppers", "Ham", "Cheese", "Peppers"); In this situation, there'd be two Peppers elements in there, in which case we would want to strip out the duplicate Peppers before running the merges and intersects. This is done by using array_unique(), which takes an array as its parameter and returns the same array with its duplicate values removed, like this: $toppings2 = array_unique($toppings2); Try the example code again, this time removing the duplicate Cheese values from $bothtoppings. 15

16 Filtering your array through a function array array_filter ( array input [, callback function]) The final array function in this group is array_filter(), which is a very powerful function that allows you to filter elements through a function you specify. If the function returns true, the item makes it into the array that is returned, otherwise it is not. Consider this script: function endswithy($value) { return (substr($value, -1) == 'y'); } $people = array("johnny", "Timmy", "Bobby", "Sam", "Tammy", "Danny", "Joe"); $withy = array_filter($people, "endswithy"); var_dump($withy); In this script we have an array of people, most of which have a name ending with "y". However, several do not, and for one reason or another we want to have a list of people whose names ends in "y", so array_filter() is used. The function endswithy() will return true if the last letter of each array value ends with a y, otherwise false. By passing that as the second parameter to array_filter(), it will be called once for every array element, passing in the value of the element as the parameter to endswithy(), where it is checked for a "y" at the end. 16

17 Converting an array to individual variables int extract ( array source [, int extract_type [, string prefix]]) Extract() is a very popular function that converts elements in an array into variables in their own right. Extract takes a minimum of one parameter, an array, and returns the number of elements extracted. This is best explained using code, so here goes: $Wales = 'Swansea'; $capitalcities['england'] = 'London'; $capitalcities['scotland'] = 'Edinburgh'; $capitalcities['wales'] = 'Cardiff'; extract($capitalcities); print $Wales; After calling extract, the "England", "Scotland", and "Wales" keys become variables in their own right ($England, $Scotland, and $Wales), with their values set to "London", "Edinburgh", and "Cardiff" respectively. By default, extract() will overwrite any existing variables, meaning that $Wales's original value of "Swansea" will be overwritten with "Cardiff". This behaviour can be altered using the second parameter, and averted using the third parameter. Parameter two takes a special constant value that allows you to decide how values will be treated if there is an existing variable, and parameter three allows you to prefix each extract variable with a special string. Here are the possible values of the second parameter: EXTR_OVERWRITE On collision, overwrite the existing variable EXTR_SKIP On collision, do not overwrite the existing variable 17

18 EXTR_PREFIX_SAME On collision, prefix the variable name with the prefix specified by parameter three EXTR_PREFIX_ALL Prefix all variables with the prefix specified by parameter three, whether or not there is a collision EXTR_PREFIX_INVALID Only use the prefix specified by parameter three when variables names would otherwise be illegal (e.g. "$9") EXTR_IF_EXISTS Only set variables if they already exist EXTR_PREFIX_IF_EXISTS Only create prefixed variables if non-prefixed version already exists EXTR_REFS Extract variables as references The last option, EXTR_REFS, can either be used on its own or in combination with others using the bitwise OR operator. Here are some examples based upon the $capitalcities array from the previous example: $Wales = 'Swansea'; extract($capitalcities, EXTR_SKIP); print $Wales; print $Scotland; extract($capitalcities, EXTR_PREFIX_SAME, "country"); print $Wales; print $country_england; extract($capitalcities, EXTR_PREFIX_ALL, "country"); On line one we pre-set $Wales to be a value so that you can clearly see how the second parameter works. On line two we call extract() using two parameters, with EXTR_SKIP as parameter two so that our $Wales will not be overwritten. However, as you will be able to see if you run the script, $England and $Scotland were set. On line five we use EXTR_PREFIX_SAME, which will extract variables and use the third parameter as a prefix if it finds any collisions. As we set $Wales ourselves 18

19 and our previous call to extract() created $England and $Scotland, all our variables will need to be prefixed. As you can see on line six, $Wales is still set to "Swansea", and on line seven we have our prefixed variable $country_england. Note that PHP places an underscore _ after your prefix to make the variable easy to read. Finally we call extract() with EXTR_PREFIX_ALL, which will unconditionally create variables with prefixes, overwriting $country_england, etc. Note that EXTR_OVERWRITE is rarely if ever used, because it is the same as using extract() without second or third parameters. 19

20 Checking whether an element exists bool in_array ( mixed needle, array haystack [, bool strict]) The in_array() function does precisely what you might think - if you pass it a value and an array it will return true if the value is in the array, otherwise false. This following example show it in action: $needle = "Sam"; $haystack = array("johnny", "Timmy", "Bobby", "Sam", "Tammy", "Danny", "Joe"); if (in_array($needle, $haystack)) { print "$needle is in the array!\n"; } else { print "$needle is not in the array\n"; } In_array() has an optional boolean third parameter (set to false by default) that defines whether you want to use strict checking or not. If parameter three is set to true, PHP will only return true if the value is in the array and it is of the same type - that is, if they are identical in the same way as the === operator (three equals signs). This is not used very often, but it is important that you are at least aware of its existence. 20

PHP Personal Home Page PHP: Hypertext Preprocessor (Lecture 35-37)

PHP Personal Home Page PHP: Hypertext Preprocessor (Lecture 35-37) PHP Personal Home Page PHP: Hypertext Preprocessor (Lecture 35-37) A Server-side Scripting Programming Language An Introduction What is PHP? PHP stands for PHP: Hypertext Preprocessor. It is a server-side

More information

PHP Syntax. PHP is a great example of a commonly-used modern programming language.

PHP Syntax. PHP is a great example of a commonly-used modern programming language. PHP is a great example of a commonly-used modern programming language. C was first released in 1972, PHP in 1995. PHP is an excellent language choice for software that requires an easy way to do things

More information

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements Programming, Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science and Engineering Indian Institute of Technology, Madras Lecture 05 I/O statements Printf, Scanf Simple

More information

Array Tips. ['Hip', 'Hip', 'Hip'] Benoit 23/03/2016 AFUP Lyon

Array Tips. ['Hip', 'Hip', 'Hip'] Benoit 23/03/2016 AFUP Lyon Array Tips ['Hip', 'Hip', 'Hip'] Benoit Viguier @b_viguier 23/03/2016 AFUP Lyon #0/3 It s about array! #1/3 Vanilla Php #2/3 $ids = []; foreach($data as $d) { $ids[] = $d['id']; } $ids = array_column(

More information

COMS 469: Interactive Media II

COMS 469: Interactive Media II COMS 469: Interactive Media II Agenda Review Data Types & Variables Decisions, Loops, and Functions Review gunkelweb.com/coms469 Review Basic Terminology Computer Languages Interpreted vs. Compiled Client

More information

PHP. Interactive Web Systems

PHP. Interactive Web Systems PHP Interactive Web Systems PHP PHP is an open-source server side scripting language. PHP stands for PHP: Hypertext Preprocessor One of the most popular server side languages Second most popular on GitHub

More information

IDM 232. Scripting for Interactive Digital Media II. IDM 232: Scripting for IDM II 1

IDM 232. Scripting for Interactive Digital Media II. IDM 232: Scripting for IDM II 1 IDM 232 Scripting for Interactive Digital Media II IDM 232: Scripting for IDM II 1 PHP HTML-embedded scripting language IDM 232: Scripting for IDM II 2 Before we dive into code, it's important to understand

More information

PHP and MySQL for Dynamic Web Sites. Intro Ed Crowley

PHP and MySQL for Dynamic Web Sites. Intro Ed Crowley PHP and MySQL for Dynamic Web Sites Intro Ed Crowley Class Preparation If you haven t already, download the sample scripts from: http://www.larryullman.com/books/phpand-mysql-for-dynamic-web-sitesvisual-quickpro-guide-4thedition/#downloads

More information

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types COMP-202 Unit 6: Arrays Introduction (1) Suppose you want to write a program that asks the user to enter the numeric final grades of 350 COMP-202

More information

What is PHP? [1] Figure 1 [1]

What is PHP? [1] Figure 1 [1] PHP What is PHP? [1] PHP is an acronym for "PHP: Hypertext Preprocessor" PHP is a widely-used, open source scripting language PHP scripts are executed on the server PHP is free to download and use Figure

More information

printf( Please enter another number: ); scanf( %d, &num2);

printf( Please enter another number: ); scanf( %d, &num2); CIT 593 Intro to Computer Systems Lecture #13 (11/1/12) Now that we've looked at how an assembly language program runs on a computer, we're ready to move up a level and start working with more powerful

More information

First Java Program - Output to the Screen

First Java Program - Output to the Screen First Java Program - Output to the Screen These notes are written assuming that the reader has never programmed in Java, but has programmed in another language in the past. In any language, one of the

More information

PHP 7.1 and SQL 5.7. Section Subject Page

PHP 7.1 and SQL 5.7. Section Subject Page One PHP Introduction 2 PHP: Hypertext Preprocessor 3 Some of its main uses 4 Two PHP Structure 5 Basic Structure of PHP 6 PHP Version etc 15 Use of Echo 17 Concatenating Echo 19 Use of Echo with Escape

More information

The Dynamic Typing Interlude

The Dynamic Typing Interlude CHAPTER 6 The Dynamic Typing Interlude In the prior chapter, we began exploring Python s core object types in depth with a look at Python numbers. We ll resume our object type tour in the next chapter,

More information

Abram Hindle Kitchener Waterloo Perl Monger October 19, 2006

Abram Hindle Kitchener Waterloo Perl Monger   October 19, 2006 OCaml Tutorial Abram Hindle Kitchener Waterloo Perl Monger http://kw.pm.org abez@abez.ca October 19, 2006 Abram Hindle 1 OCaml Functional Language Multiple paradigms: Imperative, Functional, Object Oriented

More information

Working with Functions and Classes

Working with Functions and Classes CHAPTER 5 Working with Functions and Classes IN THIS CHAPTER: 5.1 Defining Custom Functions 5.2 Avoiding Function Duplication 5.3 Accessing External Variables from Within a Function 5.4 Setting Default

More information

COMS 469: Interactive Media II

COMS 469: Interactive Media II COMS 469: Interactive Media II Agenda Review Conditional Statements String and Numeric Functions Arrays Review PHP History Rasmus Lerdorf 1995 Andi Gutmans & Zeev Suraski Versions 1998 PHP 2.0 2000 PHP

More information

PHP: Hypertext Preprocessor. A tutorial Introduction

PHP: Hypertext Preprocessor. A tutorial Introduction PHP: Hypertext Preprocessor A tutorial Introduction Introduction PHP is a server side scripting language Primarily used for generating dynamic web pages and providing rich web services PHP5 is also evolving

More information

At its simplest, a computer is a collection of wires, transistors and electrical components that are connected in a specific way When you send

At its simplest, a computer is a collection of wires, transistors and electrical components that are connected in a specific way When you send What is a computer? At its simplest, a computer is a collection of wires, transistors and electrical components that are connected in a specific way When you send certain sequences of voltages down the

More information

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are: LESSON 1 FUNDAMENTALS OF C The purpose of this lesson is to explain the fundamental elements of the C programming language. C like other languages has all alphabet and rules for putting together words

More information

These are notes for the third lecture; if statements and loops.

These are notes for the third lecture; if statements and loops. These are notes for the third lecture; if statements and loops. 1 Yeah, this is going to be the second slide in a lot of lectures. 2 - Dominant language for desktop application development - Most modern

More information

The Big Python Guide

The Big Python Guide The Big Python Guide Big Python Guide - Page 1 Contents Input, Output and Variables........ 3 Selection (if...then)......... 4 Iteration (for loops)......... 5 Iteration (while loops)........ 6 String

More information

Memory Addressing, Binary, and Hexadecimal Review

Memory Addressing, Binary, and Hexadecimal Review C++ By A EXAMPLE Memory Addressing, Binary, and Hexadecimal Review You do not have to understand the concepts in this appendix to become well-versed in C++. You can master C++, however, only if you spend

More information

Coding Workshop. Learning to Program with an Arduino. Lecture Notes. Programming Introduction Values Assignment Arithmetic.

Coding Workshop. Learning to Program with an Arduino. Lecture Notes. Programming Introduction Values Assignment Arithmetic. Coding Workshop Learning to Program with an Arduino Lecture Notes Table of Contents Programming ntroduction Values Assignment Arithmetic Control Tests f Blocks For Blocks Functions Arduino Main Functions

More information

Decaf Language Reference Manual

Decaf Language Reference Manual Decaf Language Reference Manual C. R. Ramakrishnan Department of Computer Science SUNY at Stony Brook Stony Brook, NY 11794-4400 cram@cs.stonybrook.edu February 12, 2012 Decaf is a small object oriented

More information

CLIL-3-PHP-3. Files - part 1. Once you master the art of working with files, a wider world of PHP web

CLIL-3-PHP-3. Files - part 1. Once you master the art of working with files, a wider world of PHP web Files - part 1 Introduction Once you master the art of working with files, a wider world of PHP web development opens up to you. Files aren't as flexible as databases by any means, but they do offer the

More information

x = 3 * y + 1; // x becomes 3 * y + 1 a = b = 0; // multiple assignment: a and b both get the value 0

x = 3 * y + 1; // x becomes 3 * y + 1 a = b = 0; // multiple assignment: a and b both get the value 0 6 Statements 43 6 Statements The statements of C# do not differ very much from those of other programming languages. In addition to assignments and method calls there are various sorts of selections and

More information

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #44. Multidimensional Array and pointers

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #44. Multidimensional Array and pointers Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #44 Multidimensional Array and pointers In this video, we will look at the relation between Multi-dimensional

More information

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals

More information

void setup(){ void loop() { The above setup works, however the function is limited in the fact it can not be reused easily. To make the code more gene

void setup(){ void loop() { The above setup works, however the function is limited in the fact it can not be reused easily. To make the code more gene Passing arrays to functions A big topic for beginners is how to write a function that can be passed an array. A very common way of achieving this is done using pointers. This method can be seen all through

More information

Intro. Speed V Growth

Intro. Speed V Growth Intro Good code is two things. It's elegant, and it's fast. In other words, we got a need for speed. We want to find out what's fast, what's slow, and what we can optimize. First, we'll take a tour of

More information

CHAD Language Reference Manual

CHAD Language Reference Manual CHAD Language Reference Manual INTRODUCTION The CHAD programming language is a limited purpose programming language designed to allow teachers and students to quickly code algorithms involving arrays,

More information

JQuery and Javascript

JQuery and Javascript JQuery and Javascript Javascript - a programming language to perform calculations/ manipulate HTML and CSS/ make a web page interactive JQuery - a javascript framework to help manipulate HTML and CSS JQuery

More information

UNIT- 3 Introduction to C++

UNIT- 3 Introduction to C++ UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage

More information

Definition: A data structure is a way of organizing data in a computer so that it can be used efficiently.

Definition: A data structure is a way of organizing data in a computer so that it can be used efficiently. The Science of Computing I Lesson 4: Introduction to Data Structures Living with Cyber Pillar: Data Structures The need for data structures The algorithms we design to solve problems rarely do so without

More information

By Ryan Stevenson. Guidebook #2 HTML

By Ryan Stevenson. Guidebook #2 HTML By Ryan Stevenson Guidebook #2 HTML Table of Contents 1. HTML Terminology & Links 2. HTML Image Tags 3. HTML Lists 4. Text Styling 5. Inline & Block Elements 6. HTML Tables 7. HTML Forms HTML Terminology

More information

COMP 105 Homework: Type Systems

COMP 105 Homework: Type Systems Due Tuesday, March 29, at 11:59 PM (updated) The purpose of this assignment is to help you learn about type systems. Setup Make a clone of the book code: git clone linux.cs.tufts.edu:/comp/105/build-prove-compare

More information

Here's how you declare a function that returns a pointer to a character:

Here's how you declare a function that returns a pointer to a character: 23 of 40 3/28/2013 10:35 PM Violets are blue Roses are red C has been around, But it is new to you! ANALYSIS: Lines 32 and 33 in main() prompt the user for the desired sort order. The value entered is

More information

COMP-202 Unit 4: Programming with Iterations

COMP-202 Unit 4: Programming with Iterations COMP-202 Unit 4: Programming with Iterations Doing the same thing again and again and again and again and again and again and again and again and again... CONTENTS: While loops Class (static) variables

More information

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02 Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02 Hello, in this lecture we will learn about some fundamentals concepts of java.

More information

Web Programming Step by Step

Web Programming Step by Step Web Programming Step by Step Lecture 7 PHP Syntax Reading: 5.2-5.4 Except where otherwise noted, the contents of this presentation are Copyright 2009 Marty Stepp and Jessica Miller. 5.2: PHP Basic Syntax

More information

Module 10A Lecture - 20 What is a function? Why use functions Example: power (base, n)

Module 10A Lecture - 20 What is a function? Why use functions Example: power (base, n) Programming, Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science and Engineering Indian Institute of Technology, Madras Module 10A Lecture - 20 What is a function?

More information

Client Side JavaScript and AJAX

Client Side JavaScript and AJAX Client Side JavaScript and AJAX Client side javascript is JavaScript that runs in the browsers of people using your site. So far all the JavaScript code we've written runs on our node.js server. This is

More information

C++ Data Types. 1 Simple C++ Data Types 2. 3 Numeric Types Integers (whole numbers) Decimal Numbers... 5

C++ Data Types. 1 Simple C++ Data Types 2. 3 Numeric Types Integers (whole numbers) Decimal Numbers... 5 C++ Data Types Contents 1 Simple C++ Data Types 2 2 Quick Note About Representations 3 3 Numeric Types 4 3.1 Integers (whole numbers)............................................ 4 3.2 Decimal Numbers.................................................

More information

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

Unit-II Programming and Problem Solving (BE1/4 CSE-2) Unit-II Programming and Problem Solving (BE1/4 CSE-2) Problem Solving: Algorithm: It is a part of the plan for the computer program. An algorithm is an effective procedure for solving a problem in a finite

More information

Input And Output of C++

Input And Output of C++ Input And Output of C++ Input And Output of C++ Seperating Lines of Output New lines in output Recall: "\n" "newline" A second method: object endl Examples: cout

More information

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */ Overview Language Basics This chapter describes the basic elements of Rexx. It discusses the simple components that make up the language. These include script structure, elements of the language, operators,

More information

Chapter 3: Operators, Expressions and Type Conversion

Chapter 3: Operators, Expressions and Type Conversion 101 Chapter 3 Operators, Expressions and Type Conversion Chapter 3: Operators, Expressions and Type Conversion Objectives To use basic arithmetic operators. To use increment and decrement operators. To

More information

Teaching guide: Subroutines

Teaching guide: Subroutines Teaching guide: Subroutines This resource will help with understanding subroutines. It supports Sections 3.2.2 and 3.2.10 of our current GCSE Computer Science specification (8520). The guide is designed

More information

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #13. Loops: Do - While

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #13. Loops: Do - While Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #13 Loops: Do - While So far we have been using while loops in C, now C programming language also provides you

More information

High Performance Computing Prof. Matthew Jacob Department of Computer Science and Automation Indian Institute of Science, Bangalore

High Performance Computing Prof. Matthew Jacob Department of Computer Science and Automation Indian Institute of Science, Bangalore High Performance Computing Prof. Matthew Jacob Department of Computer Science and Automation Indian Institute of Science, Bangalore Module No # 09 Lecture No # 40 This is lecture forty of the course on

More information

The Stack, Free Store, and Global Namespace

The Stack, Free Store, and Global Namespace Pointers This tutorial is my attempt at clarifying pointers for anyone still confused about them. Pointers are notoriously hard to grasp, so I thought I'd take a shot at explaining them. The more information

More information

Read this before starting!

Read this before starting! Portion of test Points possible Written: 60 Code Modification: 20 Debug/Coding: 20 Total: 100 Points missed Points correct Student's Name: East Tennessee State University Department of Computer and Information

More information

[2:3] Linked Lists, Stacks, Queues

[2:3] Linked Lists, Stacks, Queues [2:3] Linked Lists, Stacks, Queues Helpful Knowledge CS308 Abstract data structures vs concrete data types CS250 Memory management (stack) Pointers CS230 Modular Arithmetic !!!!! There s a lot of slides,

More information

CS103 Spring 2018 Mathematical Vocabulary

CS103 Spring 2018 Mathematical Vocabulary CS103 Spring 2018 Mathematical Vocabulary You keep using that word. I do not think it means what you think it means. - Inigo Montoya, from The Princess Bride Consider the humble while loop in most programming

More information

Formatting: Cleaning Up Data

Formatting: Cleaning Up Data Formatting: Cleaning Up Data Hello and welcome to our lesson on cleaning up data, which is one of the final ones in this Formatting Module. What we re going to be doing in this lesson is using some of

More information

REVIEW. The C++ Programming Language. CS 151 Review #2

REVIEW. The C++ Programming Language. CS 151 Review #2 REVIEW The C++ Programming Language Computer programming courses generally concentrate on program design that can be applied to any number of programming languages on the market. It is imperative, however,

More information

C++ Reference NYU Digital Electronics Lab Fall 2016

C++ Reference NYU Digital Electronics Lab Fall 2016 C++ Reference NYU Digital Electronics Lab Fall 2016 Updated on August 24, 2016 This document outlines important information about the C++ programming language as it relates to NYU s Digital Electronics

More information

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Object oriented programming. Instructor: Masoud Asghari Web page:   Ch: 3 Object oriented programming Instructor: Masoud Asghari Web page: http://www.masses.ir/lectures/oops2017sut Ch: 3 1 In this slide We follow: https://docs.oracle.com/javase/tutorial/index.html Trail: Learning

More information

This is the basis for the programming concept called a loop statement

This is the basis for the programming concept called a loop statement Chapter 4 Think back to any very difficult quantitative problem that you had to solve in some science class How long did it take? How many times did you solve it? What if you had millions of data points

More information

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find CS1622 Lecture 15 Semantic Analysis CS 1622 Lecture 15 1 Semantic Analysis How to build symbol tables How to use them to find multiply-declared and undeclared variables. How to perform type checking CS

More information

Example: Computing prime numbers

Example: Computing prime numbers Example: Computing prime numbers -Write a program that lists all of the prime numbers from 1 to 10,000. Remember a prime number is a # that is divisible only by 1 and itself Suggestion: It probably will

More information

Web Application Development (WAD) V th Sem BBAITM(Unit-1) By: Binit Patel

Web Application Development (WAD) V th Sem BBAITM(Unit-1) By: Binit Patel Web Application Development (WAD) V th Sem BBAITM(Unit-1) By: Binit Patel Introduction: PHP (Hypertext Preprocessor) was invented by Rasmus Lerdorf in 1994. First it was known as Personal Home Page. Later

More information

RTL Reference 1. JVM. 2. Lexical Conventions

RTL Reference 1. JVM. 2. Lexical Conventions RTL Reference 1. JVM Record Transformation Language (RTL) runs on the JVM. Runtime support for operations on data types are all implemented in Java. This constrains the data types to be compatible to Java's

More information

Variables. Data Types.

Variables. Data Types. Variables. Data Types. The usefulness of the "Hello World" programs shown in the previous section is quite questionable. We had to write several lines of code, compile them, and then execute the resulting

More information

Pointers cause EVERYBODY problems at some time or another. char x[10] or char y[8][10] or char z[9][9][9] etc.

Pointers cause EVERYBODY problems at some time or another. char x[10] or char y[8][10] or char z[9][9][9] etc. Compound Statements So far, we ve mentioned statements or expressions, often we want to perform several in an selection or repetition. In those cases we group statements with braces: i.e. statement; statement;

More information

Ruby on Rails Welcome. Using the exercise files

Ruby on Rails Welcome. Using the exercise files Ruby on Rails Welcome Welcome to Ruby on Rails Essential Training. In this course, we're going to learn the popular open source web development framework. We will walk through each part of the framework,

More information

Starting To Write PHP Code

Starting To Write PHP Code Starting To Write PHP Code April 22 nd 2014 Thomas Beebe Advanced DataTools Corp (tom@advancedatatools.com) Tom Beebe Tom is a Senior Database Consultant and has been with Advanced DataTools for over 10

More information

COMP284 Scripting Languages Lecture 10: PHP (Part 2) Handouts

COMP284 Scripting Languages Lecture 10: PHP (Part 2) Handouts COMP284 Scripting Languages Lecture 10: PHP (Part 2) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

5. Excel Fundamentals

5. Excel Fundamentals 5. Excel Fundamentals Excel is a software product that falls into the general category of spreadsheets. Excel is one of several spreadsheet products that you can run on your PC. Others include 1-2-3 and

More information

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture - 08 Constants and Inline Functions Welcome to module 6 of Programming

More information

Databases on the web

Databases on the web Databases on the web The Web Application Stack Network Server You The Web Application Stack Network Server You The Web Application Stack Web Browser Network Server You The Web Application Stack Web Browser

More information

PHP Functions and Arrays. Orlando PHP Meetup Zend Certification Training March 2009

PHP Functions and Arrays. Orlando PHP Meetup Zend Certification Training March 2009 PHP Functions and Arrays Orlando PHP Meetup Zend Certification Training March 2009 Functions Minimal syntax function name() { } PHP function names are not case-sensitive. All functions in PHP return a

More information

egrapher Language Reference Manual

egrapher Language Reference Manual egrapher Language Reference Manual Long Long: ll3078@columbia.edu Xinli Jia: xj2191@columbia.edu Jiefu Ying: jy2799@columbia.edu Linnan Wang: lw2645@columbia.edu Darren Chen: dsc2155@columbia.edu 1. Introduction

More information

A brief introduction to C programming for Java programmers

A brief introduction to C programming for Java programmers A brief introduction to C programming for Java programmers Sven Gestegård Robertz September 2017 There are many similarities between Java and C. The syntax in Java is basically

More information

Lecture Notes on Memory Layout

Lecture Notes on Memory Layout Lecture Notes on Memory Layout 15-122: Principles of Imperative Computation Frank Pfenning André Platzer Lecture 11 1 Introduction In order to understand how programs work, we can consider the functions,

More information

BEGINNER PHP Table of Contents

BEGINNER PHP Table of Contents Table of Contents 4 5 6 7 8 9 0 Introduction Getting Setup Your first PHP webpage Working with text Talking to the user Comparison & If statements If & Else Cleaning up the game Remembering values Finishing

More information

ORB Education Quality Teaching Resources

ORB Education Quality Teaching Resources JavaScript is one of the programming languages that make things happen in a web page. It is a fantastic way for students to get to grips with some of the basics of programming, whilst opening the door

More information

JME Language Reference Manual

JME Language Reference Manual JME Language Reference Manual 1 Introduction JME (pronounced jay+me) is a lightweight language that allows programmers to easily perform statistic computations on tabular data as part of data analysis.

More information

The action of the program depends on the input We can create this program using an if statement

The action of the program depends on the input We can create this program using an if statement The program asks the user to enter a number If the user enters a number greater than zero, the program displays a message: You entered a number greater than zero Otherwise, the program does nothing The

More information

Let's Look Back. We talked about how to create a form in HTML. Forms are one way to interact with users

Let's Look Back. We talked about how to create a form in HTML. Forms are one way to interact with users Introduction to PHP Let's Look Back We talked about how to create a form in HTML Forms are one way to interact with users Users can enter information into forms which can be used by you (programmer) We

More information

Figure 1 Common Sub Expression Optimization Example

Figure 1 Common Sub Expression Optimization Example General Code Optimization Techniques Wesley Myers wesley.y.myers@gmail.com Introduction General Code Optimization Techniques Normally, programmers do not always think of hand optimizing code. Most programmers

More information

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs.

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs. Lesson 2 VARIABLES Aim Understanding how computer programs store values, and how they are accessed and used in computer programs. WHAT ARE VARIABLES? When you input data (i.e. information) into a computer

More information

JavaScript Functions, Objects and Array

JavaScript Functions, Objects and Array JavaScript Functions, Objects and Array Defining a Function A definition starts with the word function. A name follows that must start with a letter or underscore, followed by any number of letters, digits,

More information

Chapter 2: Functions and Control Structures

Chapter 2: Functions and Control Structures Chapter 2: Functions and Control Structures TRUE/FALSE 1. A function definition contains the lines of code that make up a function. T PTS: 1 REF: 75 2. Functions are placed within parentheses that follow

More information

CS106X Handout 03 Autumn 2012 September 24 th, 2012 Getting Started

CS106X Handout 03 Autumn 2012 September 24 th, 2012 Getting Started CS106X Handout 03 Autumn 2012 September 24 th, 2012 Getting Started Handout written by Julie Zelenski, Mehran Sahami, Robert Plummer, and Jerry Cain. After today s lecture, you should run home and read

More information

ASML Language Reference Manual

ASML Language Reference Manual ASML Language Reference Manual Tim Favorite (tuf1) & Frank Smith (fas2114) - Team SoundHammer Columbia University COMS W4115 - Programming Languages & Translators 1. Introduction The purpose of Atomic

More information

Chapter 2 Working with Data Types and Operators

Chapter 2 Working with Data Types and Operators JavaScript, Fourth Edition 2-1 Chapter 2 Working with Data Types and Operators At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics

More information

CS1004: Intro to CS in Java, Spring 2005

CS1004: Intro to CS in Java, Spring 2005 CS1004: Intro to CS in Java, Spring 2005 Lecture #16: Java conditionals/loops, cont d. Janak J Parekh janak@cs.columbia.edu Administrivia Midterms returned now Weird distribution Mean: 35.4 ± 8.4 What

More information

B. V. Patel Institute of BMC & IT 2014

B. V. Patel Institute of BMC & IT 2014 Unit 1: Introduction Short Questions: 1. What are the rules for writing PHP code block? 2. Explain comments in your program. What is the purpose of comments in your program. 3. How to declare and use constants

More information

Instructor s Notes Web Data Management PHP Sequential Processing Syntax. Web Data Management PHP Sequential Processing Syntax

Instructor s Notes Web Data Management PHP Sequential Processing Syntax. Web Data Management PHP Sequential Processing Syntax Instructor s Web Data Management PHP Sequential Processing Syntax Web Data Management 152-155 PHP Sequential Processing Syntax Quick Links & Text References PHP tags in HTML Pages Comments Pages 48 49

More information

Computers Programming Course 6. Iulian Năstac

Computers Programming Course 6. Iulian Năstac Computers Programming Course 6 Iulian Năstac Recap from previous course Data types four basic arithmetic type specifiers: char int float double void optional specifiers: signed, unsigned short long 2 Recap

More information

PHP 5 Introduction. What You Should Already Know. What is PHP? What is a PHP File? What Can PHP Do? Why PHP?

PHP 5 Introduction. What You Should Already Know. What is PHP? What is a PHP File? What Can PHP Do? Why PHP? PHP 5 Introduction What You Should Already Know you should have a basic understanding of the following: HTML CSS What is PHP? PHP is an acronym for "PHP: Hypertext Preprocessor" PHP is a widely-used, open

More information

Copyright (c) by Matthew S. Harris

Copyright (c) by Matthew S. Harris Documentation & How-To Didjiman's Forms Instance Manager Class For MS Access 2007 and Higher Version v2017-03-28 Copyright (c) 2014-2017 by Matthew S. Harris Permission is granted to copy, distribute and/or

More information

QUIZ. What is wrong with this code that uses default arguments?

QUIZ. What is wrong with this code that uses default arguments? QUIZ What is wrong with this code that uses default arguments? Solution The value of the default argument should be placed in either declaration or definition, not both! QUIZ What is wrong with this code

More information

CS113: Lecture 3. Topics: Variables. Data types. Arithmetic and Bitwise Operators. Order of Evaluation

CS113: Lecture 3. Topics: Variables. Data types. Arithmetic and Bitwise Operators. Order of Evaluation CS113: Lecture 3 Topics: Variables Data types Arithmetic and Bitwise Operators Order of Evaluation 1 Variables Names of variables: Composed of letters, digits, and the underscore ( ) character. (NO spaces;

More information

Functions, Pointers, and the Basics of C++ Classes

Functions, Pointers, and the Basics of C++ Classes Functions, Pointers, and the Basics of C++ Classes William E. Skeith III Functions in C++ Vocabulary You should be familiar with all of the following terms already, but if not, you will be after today.

More information

CS2141 Software Development using C/C++ C++ Basics

CS2141 Software Development using C/C++ C++ Basics CS2141 Software Development using C/C++ C++ Basics Integers Basic Types Can be short, long, or just plain int C++ does not define the size of them other than short

More information

Conditionals and Loops

Conditionals and Loops Conditionals and Loops Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing steps in a loop Chapter 5 focuses on: boolean expressions conditional

More information