of 39

• date post

21-Jan-2016
• Category

## Documents

• view

56

0

Embed Size (px)

description

Guest Speaker - Cryptography. Wednesday (Apr. 22) – Prof. abhi shelat. Final Exam Review. Built-In Datatypes. Variables. A variable has three parts: Name (e.g., “ x ”) Type (e.g., int , double , String ) Value How does a variable get a value? Can be initialized in the program - PowerPoint PPT Presentation

### Transcript of Guest Speaker - Cryptography

• Guest Speaker - CryptographyWednesday (Apr. 22) Prof. abhi shelat

• Final Exam Review

CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright 2007 http://www.cs.Princeton.EDU/IntroCS

Built-In Datatypes

• VariablesA variable has three parts:Name (e.g., x)Type (e.g., int, double, String)Value

How does a variable get a value?Can be initialized in the programE.g., int x = 10Can be computed when the program is runningE.g., x = y + z;

• *Built-in Data TypesData type. A set of values and operations defined on those values.add, subtract, multiply, divide3.14156.022e23floating point numbersdoubleadd, subtract, multiply, divide1712345integersintand, or, nottruefalsetruth valuesbooleansequences of characterscharactersset of valuesoperationsliteral valuestypecompare'A''@'charStringconcatenate"Hello World""CS is fun"

• *Math Library

• *Type ConversionType conversion. Convert from one type of data to another.Automatic: no loss of precision; or with strings.Explicit: cast; or method.

• Conditionals and Loops

• *Control Flow SummaryControl flow.Sequence of statements that are actually executed in a program.Conditionals and loops: enables us to choreograph the control flow.

Straight-line programsAll statements are executed in the order given.ConditionalsCertain statements are executed depending on the values of certain variables.ifif-elseLoopsCertain statements are executed repeatedly until certain conditions are met.whilefordo-whileControl FlowDescriptionExamples

• Nesting Conditionals and LoopsNest conditionals within conditionals.

Nest loops within loops.

Nest conditionals within loops within loops.*

• Monte Carlo SimulationGeneral Code Structure:

class MonteCarloSimulation {

for(i=0; i

• Single-Dimensional Arrays

• *Arrays in JavaJava has special language support for arrays.To make an array: declare, create, and initialize it.To access element i of array named a, use a[i]. Array indices start at 0.

Compact alternative. Declare, create, and initialize in one statement.Default initialization: all numbers automatically set to zero.int N = 10; double[] a; // declare the arraya = new double[N]; // create the arrayfor (int i = 0; i < N; i++) // initialize the array a[i] = 0.0; // all to 0.0int N = 10;double[] a = new double[N]; // declare, create, init

• Array Layout in MemoryMemory is split into equal sized units known as addresses. (Address Space)

Arrays occupy consecutive addresses in this linear space: int[] a = {5, 6, 10};

Key Point: Name of the array indirectly references its starting address.int[] b = new int[3]; b=a;//b is an alias to a. REFERENCE TYPE

*0 1 2 . . . N-2 N-1 Addresses

• Array LengthThe array length can be obtained using the .length operatorfor(i=0; i< myArray.length; i++)

The array length cannot be changed after memory allocationCan use arraylists to get around this limitation*

• Auto-incrementAuto-increment and auto-decrement operators used with arrays.++i means add one to is value and use the updated valuei++ means use is value now and then add one to the old valueCan use on line by itself as a single statementIn which case they do exactly the same thing!Differences between the auto-increment operators are important when used in expressions: y = 0; x = y++; y = 0; z = ++y;

*Y=0; x = y; y = y+1;Y=0; y = y+1; z = y;

• Multidimensional Arrays

• *Two Dimensional Arrays in JavaArray access. Use a[i][j] to access element in row i and column j.

Zero-based indexing. Row and column indices start at 0.

double[][] a = new double[10][3];for (int i = 0; i < 10; i++) { for (int j = 0; j < 3; j++) { a[i][j] = 0.0; }}Declaring and Initializing a 10-by-3 Array

• Memory Layout 2-D Arrays*Rowarray[0]array[1]array[2]array[3]array[0][0]array[1][2]

• Ragged ArraysRow lengths can be non-uniform

Can use .length

int[][] a = ...;

for (int rows=0; rows < a.length; rows++) {for (int cols=0; cols < a[rows].length; cols++) System.out.print(" " + a[rows][cols]);System.out.println("");}

*Number of rowsNumber of columns for a given row

• Functions/Static Methods

• Components of a Function

• *Flow Control Call by ValueCall by reference For reference types (arrays, objects)

Scoping Rules for functions and conditional and loop code-blocks

• Recursion

• *RecursionWhat is recursion? When one function calls itself directly or indirectly.

Gcd. Find largest integer d that evenly divides into p and q.

base casereduction steppublic static int gcd(int p, int q) { if (q == 0) return p; else return gcd(q, p % q);}base casereduction step, converges to base case

• *How-Tos on Writing Recursive FunctionsBase Case: You must check if weve reached the base case before doing another level of recursion!

Make Progress Towards Base Case:Your recursive calls must be on a smaller or simpler input. Eventually this must reach the base case (and not miss it).

Multiple recursive calls:Sometimes more than one recursive call.H-Tree, Towers of HanoiAre their return values chosen, combined?

• Objects

• *ObjectsObject. An entity that can take on a data type value.

An objects value can be returned to a client or be changed by one of the data types operations.

length, substring, comparesequence of charactersStringOperationsSet of ValuesData Typeget red component, brighten24 bitsColorPictureget/set color of pixel (i, j)2D array of colors

• Things to Remember About ObjectsClass APIConstructorInstance Methods

Difference between constructors and methods

• Assigning one object/array to another object/array results in an aliasCannot use == operator to check the equality of objectsUse instance method equals(). Can define this method for any class.

Mutable vs. Immutable ObjectsImmutable Cant change the value of an object after its createdAliases to immutable objects are less problematic

*Objects are Reference Types

• Principles of Object Oriented ProgrammingEncapsulation: Combine data and the functions that operate on that data into a single unit (object)

Data Hiding: Clients should not be able to manipulate data in objects directly

Declare instance variables to be privateUse getter methods to read data within objects

Any object should be able to invoke the instance methodsDeclare instance methods to be public

• *Summary of Classes

(Charge Class Discussed in the Textbook)

• Data Structures

• *Data StructuresListsA collection of a variable number of items

Typical Operations on ListsAdd an item to the listRemove an item from the listRead an item from the listCheck whether the list is emptyGet the current size of the list

All of these are provided via the Java ArrayList class

• *Generics. Parameterize the datatype used in the data structure.

You need to import the library: import java.util.ArrayList;

*GenericsArrayList list= new ArrayList();Apple a = new Apple();Orange b = new Orange();list.add(a);list.add(b); // compile-time errora = list.get(0); // returns an Apple objectsample client

• **AutoboxingGeneric ArrayList implementation. Only permits reference types.

Wrapper type.Each primitive type has a wrapper reference type.Ex: Integer is wrapper type for int.

Autoboxing. Automatic cast from primitive type to wrapper type.Autounboxing. Automatic cast from wrapper type to primitive type.

ArrayList list= new ArrayList();list.add(17); // autobox (int -> Integer)int a = list.get(i); // autounbox (Integer -> int)

• *Lists Can Be Organized in Different WaysLinked ListLinear sequence of elements

QueueRemove the item least recently added.First-In, First-Out (FIFO)

StackRemove the item most recently added. Last-In, First-Out (LIFO)

Array Implementation vs. ArrayList Implementation

• Guest Speaker - CryptographyWednesday (Apr. 22) Prof. abhi shelat

***Your program operates on a lot of different types of data. So the programming language needs to provide you a way of specifying the types of data you are using and allow you to manipulate them the way you want. Built-in data types are part of Java itself.*(1) Explain each column first.****Mention do-while loop loop-body executed one first.***The array could be placed anywhere in the range of addresses.Every array element has a unique memory address.The value within an address may change but the address itself remains the same.Since arrays are variable in length, the compiler cannot just depend on the declaration to allocate memory. Need an explicit memory allocation step.********1) What is your first impression of this code?*How would you implement gcd?******1) Change String to ints in the sample code.*syntactic sugar: casts are still done behind the scenes (hidden cost)*