COMP-202: Foundations of Programming. Lecture 9: Arrays and Practice Jackie Cheung, Winter 2016

Similar documents
COMP-202: Foundations of Programming. Lecture 7: Strings and Methods Jackie Cheung, Winter 2015

COMP-202: Foundations of Programming. Lecture 5: Arrays, Reference Type, and Methods Sandeep Manjanna, Summer 2015

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015

COMP-202: Foundations of Programming. Lecture 8: for Loops, Nested Loops and Arrays Jackie Cheung, Winter 2016

COMP-202: Foundations of Programming

COMP-202: Foundations of Programming. Lecture 5: More About Methods and Data Types Jackie Cheung, Winter 2016

CONTENTS: Arrays Strings. COMP-202 Unit 5: Loops in Practice

COMP-202: Foundations of Programming. Lecture 16: Reference types Jackie Cheung, Winter 2016

COMP-202: Foundations of Programming. Lecture 26: Review; Wrap-Up Jackie Cheung, Winter 2016

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java

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

Ex: If you use a program to record sales, you will want to remember data:

COMP-202: Foundations of Programming. Lecture 2: Java basics and our first Java program! Jackie Cheung, Winter 2016

Strings. Strings and their methods. Mairead Meagher Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

COMP 202 Java in one week

COMP-202: Foundations of Programming. Lecture 26: Image Manipulation; Wrap-Up Jackie Cheung, Winter 2015

COMP-202: Foundations of Programming. Lecture 12: Classes Jackie Cheung, Winter 2016

Object-Oriented Programming

ECE2049: Homework 1. Due: Thursday, 25 May 2017 by 7pm

COMP-202: Foundations of Programming. Lecture 2: Java basics and our first Java program! Jackie Cheung, Winter 2015

Linked lists Tutorial 5b

Last Class. More on loops break continue A bit on arrays

COMP-202: Foundations of Programming. Lecture 13: Recursion Sandeep Manjanna, Summer 2015

COMP-202: Foundations of Programming. Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015

COMP-202: Foundations of Programming. Lecture 6: Conditionals Jackie Cheung, Winter 2016

Programming with Java

Object Oriented Programming and Design in Java. Session 2 Instructor: Bert Huang

1B1b Classes in Java Part I

First of all, it is a variable, just like other variables you studied

Worksheet - Reading Guide for Keys and Passwords

CS211 Computers and Programming Matthew Harris and Alexa Sharp July 9, Boggle

COMP-202 Unit 7: More Advanced OOP. CONTENTS: ArrayList HashSet (Optional) HashMap (Optional)

CS61C Machine Structures. Lecture 3 Introduction to the C Programming Language. 1/23/2006 John Wawrzynek. www-inst.eecs.berkeley.

Introduction to Programming (Java) 4/12

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

CS 106A, Lecture 9 Problem-Solving with Strings

COMP 202 Recursion. CONTENTS: Recursion. COMP Recursion 1

ENGR/CS 101 CS Session Lecture 5

Arrays. Here is the generic syntax for an array declaration: type[] <var_name>; Here's an example: int[] numbers;

"Hello" " This " + "is String " + "concatenation"

CS 302: Introduction to Programming

CS1004: Intro to CS in Java, Spring 2005

Lesson 2A Data. Data Types, Variables, Constants, Naming Rules, Limits. A Lesson in Java Programming

Datatypes, Variables, and Operations

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

An Introduction to Processing

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

COE318 Lecture Notes Week 4 (Sept 26, 2011)

York University Department of Electrical Engineering and Computer Science. Regular Expressions

Getting started with Java

Garbage Collection (1)

Computing with Strings. Learning Outcomes. Python s String Type 9/23/2012

Python allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid:

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

Primitive Types. Four integer types: Two floating-point types: One character type: One boolean type: byte short int (most common) long

CSC 108H: Introduction to Computer Programming. Summer Marek Janicki

CS260 Intro to Java & Android 03.Java Language Basics

Data types Expressions Variables Assignment. COMP1400 Week 2

CS242 COMPUTER PROGRAMMING

Software and Programming 1

CS 106A, Lecture 9 Problem-Solving with Strings

VARIABLES AND TYPES CITS1001

Use of scanf. scanf("%d", &number);

Lecture 1: Perfect Security

Memory and C++ Pointers

CS 302: INTRODUCTION TO PROGRAMMING. Lectures 7&8

ECE2049 HW #1-- C programming and Binary Number Representations (DUE 9/1/2017 At the BEGINNING of class)

More on variables and methods

1 class Lecture2 { 2 3 "Elementray Programming" / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch.

CS558 Programming Languages

Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

COMP6700/2140 Data and Types

Identifiers and Variables

Java Identifiers, Data Types & Variables

Fall 2017 CISC124 9/16/2017

6.170 Laboratory in Software Engineering Java Style Guide. Overview. Descriptive names. Consistent indentation and spacing. Page 1 of 5.

Building Java Programs

SCoLang - Language Reference Manual

Chapter 1 Getting Started

ME 172. Lecture 2. Data Types and Modifier 3/7/2011. variables scanf() printf() Basic data types are. Modifiers. char int float double

Algorithms and Programming I. Lecture#12 Spring 2015

Slide 1 CS 170 Java Programming 1 More on Strings Duration: 00:00:47 Advance mode: Auto

Computational Expression

Introduction to Programming Using Java (98-388)

cs3157: another C lecture (mon-21-feb-2005) C pre-processor (3).

Primitive vs Reference

Arrays. myints = new int[15];

Building Java Programs

Text. Text Actions. String Contains

ADTs, Arrays, Linked Lists

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

CS-202 Introduction to Object Oriented Programming

COMP-202. Recursion. COMP Recursion, 2011 Jörg Kienzle and others

COMP-202 Unit 2: Java Basics. CONTENTS: Printing to the Screen Getting input from the user Types of variables Using Expressions and Variables

Primitive Data, Variables, and Expressions; Simple Conditional Execution

COMP-202 Unit 9: Exceptions

Fault, Error, and Failure

Chapter 6 Classes and Objects

Transcription:

COMP-202: Foundations of Programming Lecture 9: Arrays and Practice Jackie Cheung, Winter 2016

Review: for Loops for (initialization; condition; update) { Happens once per loop only, before the first check of the condition // loop body Happens before every iteration. If it evaluates to true, the loop body will run. } Happens at the end of every iteration. Usually used to update a variable declared in the initialization. 2

Review: Arrays What are the two key properties of arrays? Declaration: type[] var_name; Initialization: Method 1: type[] var_name = {val1, val2, val3, }; Method 2: type[] var_name = new type[size]; 3

Using An Array When you create an array of size n, you are creating n contiguous places in memory to store values of the same type. Refer to each element by its index, starting from 0. String[] instructors = {"John", "Jackie", "Bentley"}; instructors[0] instructors[1] instructors[2] "John" "Jackie" "Bentley" 4

This Lecture More about Arrays Intro to Reference Types Lots of practice with loops, arrays and Strings! 5

Need to Initialize Values What happens if we do this? String[] names = new String[35]; // print first name System.out.println(names[0]); We get a null because we've created a place to store a String, but we haven't set its value yet. Remember to initialize the entries of your arrays if you use method 2! 6

Common Array Problems 1 Referring to an index that doesn't exist. ArrayIndexOutOfBounds exception int[] x = {1, 2, 3}; System.out.println(x[-1]); System.out.println(x[3]); 7

Common Array Problems 2 Trying to access an array when the array variable is not pointing to any data. NullPointerException int[] x; System.out.println(x.length); 8

Objects Arrays and Strings are Objects. In fact, except for the primitive data types (the ones that start with lowercase, like int, double, float, byte, boolean, etc.), everything in Java is an Object. Objects are data bundled with methods to work with the data, and properties. 9

Methods of Objects Some String methods:.equals(),.length(),.tolowercase() In general: object.method_name() Arrays have no methods. Instead, they have a property called length.length Because this is not a method, there is no () after 10

Reference Types Things are about to get confusing 11

Objects Using Reference Types The variables of objects, including arrays, don't directly store the values of the objects. Instead, they store a reference to the location in memory containing the value. Think of this as storing an address, which points to where the data is actually located in memory. 12

int vs int[] int val = 42; int[] vals = {42, 37}; 42 3480 University St. int val int[] vals Meanwhile, at 3480 University St: 42, 37 13

Try It Out! Let s try creating a int array with some values, then printing it out in DrJava. i.e., int[] arr = {1,2,3,4,5}; System.out.println(arr); 14

Consequences: Assignment int[] x = {1, 2, 3}; int[] y = x; y[0] = 2; System.out.println(x[0]); What's happening here? 15

Consequences: Equality int[] arr1 = {1, 2, 3}; int[] arr2 = {1, 2, 3}; System.out.println(arr1 == arr2); This is also why we have to use.equals() to compare the values of Strings. 16

Exercise Write a method that takes an int array as input, and prints the elements out, separated by a comma and a space. e.g., int[] arr = {1,2,3,4}; printarray(arr); // prints 1, 2, 3, 4 17

Exercise Write some code that actually copies an array of ints (i.e., not just make it point to the same part of memory). e.g., int[] arr1 = {1, 4, 3, 6, 7}; int[] arr2; // make arr2 have a copy of the data in arr1 18

More about Strings STRINGS 19

String vs char[] A String is just a fancy version of char[] both store an array of char values. A String has in addition: Useful methods like.equals(),.tolowercase(),.length() A special way to be created, using "" syntax (So we don't have to go {'H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd'} as for a char[].) 20

More String Methods.charAt(int i) Gets the ith char of a String (starting from 0).substring(int a, int b) Gets the substring starting at position a with length b..compareto(string other).indexof(char c).tolowercase().touppercase() Tells you which String comes first, orthographically. Gets the index of the first occurrence of c Gets a lower-case version of the String. Gets an upper-case version of the String 21

Exercise Write some code that turns a String into a format that is like a name i.e., the first letter is capitalized, and all subsequent ones are not. "bob" "Bob" "BOB" "Bob" "BoB" "Bob" "bob" "Bob" Hint: use the methods Character.toLowerCase(char ch) and/or Character.toUpperCase(char ch) 22

Caesar Cipher Used in the ancient Roman army to obscure important messages ATTACKATMIDNIGHT* DWWDFNDWPLGQLJKW Encrypt by shifting all letters by three positions A (1 st letter) D (4 th letter) T (20 th letter) W (23 rd letter) *Ancient Romans didn't use lowercase letters, or spaces 23

Exercise Implement the encryption algorithm for a Caesar cipher Steps: Read each character of the plaintext Convert it to its numerical value Add 3 Tricky: implement wrap-around (e.g., Z C) Convert it back to a char, and save it or print it out 24

Variants ROT13 Shift by 13 instead of 3 In fact, can shift by any number of letters. Harder: arbitrary mapping between letters, not necessarily in order. This is called a letter substitution cipher. It turns out you can train a computer to crack letter substitution ciphers if you know what language the text is in! 25