Michele Van Dyne Museum 204B mvandyne@mtech.edu http://katie.mtech.edu/classes/csci136 CSCI 136: Fundamentals of Computer Science II, Spring 2016 1
Review of Java Basics Data Types Arrays NEW: multidimensional arrays Boolean Expressions Conditionals: if-else NEW: switch Iteration: while and for loops NEW: alternate for loop syntax NEW: break and continue Recursion CSCI 136: Fundamentals of Computer Science II, Spring 2016 2
Variables Primitive (and Basic) Data Types and Operations Type Conversion CSCI 136: Fundamentals of Computer Science II, Spring 2016 3
int a; a = 10; int b; b = 7; int c = a + b; Declaration statement I'm going to need an integer and let's call it a NOTE: in Java you are required to declare a variable before using it! Variable name Whenever I say a, I mean the value stored in a Literal I want the value 10 Assignment statement Variable b gets the literal value 7 = in CS is not the same as = in math! Combined declaration and assignment Make me an integer variable called c and assign it the value obtained by adding together a and b CSCI 136: Fundamentals of Computer Science II, Spring 2016 4 4
Java built-in type String what it stores example values sequence of characters "Hello world!" "I love this!" operations concatenate char characters 'a', 'b', '!' compare int integer values 42 1234 double floatingpoint values 9.95 3.0e8 boolean truth values true false add, subtract, multiply, divide, remainder add, subtract, multiply, divide and, or, not Remember a data type is a set of legal values and the operations defined on those values 5
Automatic conversion Numeric types: If no loss of precision automatic promotion String concatenation using the + operator converts numeric types to also be a String Converting from one type to another: Manually using a cast A cast is accomplished by putting a type inside ()'s ordertotal = (int) (costitem * 1.06); Casting to int drops fractional part Does not round! Using Static Methods int qty = Integer.parseInt(args[1]); double cst = Double.parseDouble(args[2]); 6
Single Dimensional (1D) Arrays Two Dimensional (2D) Arrays Multi-Dimensional (3+D)Arrays CSCI 136: Fundamentals of Computer Science II, Spring 2016 7
x[0] x[1] x[2] x[3] x[4] x[5] x[6] x[i] Declare and create: Check length: x int [] x = new int[7]; x.length Set a value: x[0] = 0; Obtain a value: x[0], x[1],..., x[6] 8
Declaring and creating Like 1D, but another pair of brackets: final int DAYS = 7; final int HOURS = 24; double [][] a = new double[days][hours]; Accessing elements To specify element at the i th row and j th column: a[i][j] How many rows? How many columns in a row? a.length a[row].length a[0][0] a[0][1] a[0][2]... a[0][22] a[0][23] a[1][0] a[1][1] a[1][2] a[1][22] a[1][23] 9
An array element can be an array 2D array is really an array of arrays a[0][0] a[0][1] a[0][2] a[0][3]... a[0][22] a[0][23] a[1][0] a[1][1] a[1][2] a[1][3]... a[1][22] a[1][23] a[0] a[1] a[2] a[3] a[4] a[5] a[6] 10
Arrays can have > 2 dimensions Use as many []'s as dimensions e.g. Game with a building consisting of 10 floors, each floor being a grid of 100 x 100 positions final int X_MAX = 100; final int Y_MAX = 100; final int FLOORS = 10; Avatar [][][] avatars = new Avatar[X_MAX][Y_MAX][FLOORS]; // Create the first player in the middle of the first floor avatars[49][49][0] = new Avatar(); 11
Results of Comparisons Logical Operators Combining Operations CSCI 136: Fundamentals of Computer Science II, Spring 2016 12
Given two numbers return a boolean operator meaning true example false example == equal 7 == 7 7 == 8!= not equal 7!= 8 7!= 7 < less than 7 < 8 8 < 7 <= less than or equal 7 <= 7 8 <= 7 > greater than 8 > 7 7 > 8 >= greater than or equal 8 >= 2 8 >= 10 13
logical AND logical OR logical NOT &&! Note: two symbols for logical AND and OR uses lazy evaluation One symbol (&, ) forces full evaluation a b a && b a b false false false false a!a true false false true false true false true true false false true true true true true 14
if-else Nested if switch CSCI 136: Fundamentals of Computer Science II, Spring 2016 15
Evaluate a boolean expression, inside the ()'s If true, do some stuff [optional] If false, do some other stuff if (expression) statement1; statement2; if (expression) statement1; statement2; else statement3; statement4; 16
Execute one of three options: if (category == 0) title = "Books"; else if (category == 1) title = "CDs"; else title = "Misc"; == if (category == 0) title = "Books"; else if (category == 1) title = "CDs"; else title = "Misc"; 17
Do something depending on a value value if-else if-else if... statements can get tedious Set a String variable monthstr to a string according to the integer value in the day variable. if (day == 1) monthstr = "Monday"; else if (day == 2) monthstr = "Tuesday"; else if (day == 3) monthstr = "Wednesday"; else if (day == 4) monthstr = "Thursday"; else if (day == 5) monthstr = "Friday"; else if (day == 6) monthstr = "Saturday"; else if (day == 7) monthstr = "Sunday"; else monthstr = "Invalid day!"; 18
switch statement Works with: byte, short, char, int, enumerations, String switch (day) case 1: monthstr = "Monday"; break; case 2: monthstr = "Tuesday"; break; case 3: monthstr = "Wednesday"; break; case 4: monthstr = "Thursday"; break; case 5: monthstr = "Friday"; break; case 6: monthstr = "Saturday"; break; case 7: monthstr = "Sunday"; break; default: monthstr = "Invalid day!"; break; case block normally ends with a break default block is optional, but if present executes if no other case matched. Like the else in an if-else if-else statement. 19
final int NORTH = 0; final int SOUTH = 1; final int EAST = 2; final int WEST = 3; int direction = 0; switch (direction) case NORTH: y--; System.out.println("Walking north"); break; case SOUTH: y++; System.out.println("Walking south"); break; case EAST: x++; System.out.println("Walking east"); break; case WEST: x--; System.out.println("Walking west"); break; You can have as many statements as you want between case and break. 20
final int NORTH = 0; final int SOUTH = 1; final int EAST = 2; final int WEST = 3; int direction = 0; switch (direction) case NORTH: y--; System.out.println("Walking north"); case SOUTH: y++; System.out.println("Walking south"); case EAST: x++; System.out.println("Walking east"); case WEST: x--; System.out.println("Walking west"); case block will fall through to next block if no break! Output: Walking north Walking south Walking east Walking west 21
int direction = 0; switch (direction) case NORTHWEST: case NORTHEAST: case NORTH: System.out.println("Heading northbound!"); break; case SOUTHWEST: case SOUTHEAST: case SOUTH: System.out.println("Walking southbound!"); break; Sometimes falling through to next case block is what you want. Easy way to do same thing for a set of discrete values. Output: Heading southbound 22
while loops while do while for loops non-enhanced enhanced break and continue CSCI 136: Fundamentals of Computer Science II, Spring 2016 23
while loop: common way to repeat code Evaluate a boolean expression If true, do a block a code Go back to start of while loop If false, skip over block while (expression) statement1; statement2; while loop with multiple statements in a block while (expression) statement1; while loop with a single statement 24
do while loop Always executes loop body at least once Do a block a code Evaluate a boolean expression If expression true, do block again do statement1; statement2; while (condition); do while needs this semicolon! 25
for loop: another common type of loop Execute an initialization statement Evaluate a boolean expression If true, do code block then increment If false, done with loop for (init; expression; increment) statement1; statement2; 26
Declare and initialize a variable for use inside and outside the loop body long sum = 0; Condition which must be true to execute loop body Changes the loop counter variable Declare and initialize a loop control variable for (int i = 1; i <= limit; i++) sum += i; System.out.println("sum 0..." + i + " = " + sum); Loop body, executes 0 or more times 27
Enhanced for loop: another type of for loop for arrays Declare an iteration variable(var below) of the same type as the array Specify the array to step through (vararray below) The loop will perform the block of statements for each element of the array, with var taking on the value of the array element for (type var:vararray) statement1; statement2; 28
Example int [ ] arr = 0, 1, 2, 3, 4, 5; for (int x:arr) System.out.println(x+7); 7 8 9 10 11 12 Output 29
Loops normally go until loop condition false break statement int i = 0 while (i < 100) // Do some stuff i++; for (int i = 0; i < 100; i++) // Do some stuff Exit a loop immediately No iteration, no increment No condition check Straight to the code after loop 30
break statement Terminates enclosing loop: for, while, or do-while Goal: sum data array, check for invalid negative values int [] data = 1, 2, 10, 5, -1, 5, 0; int i = 0; int sum = 0; while (i < data.length) if (data[i] < 0) break; sum += data[i]; i++; if (i < data.length) System.out.println("Invalid data!"); else System.out.println("Sum: " + sum); 31
Skip rest of for-loop, while-loop, do-while body Goal: sum data array, skipping invalid negative values int [] data = 1, 2, 10, 5, -1, 5, 0; int i = 0; int sum = 0; for (i = 0; i < data.length; i++) if (data[i] < 0) continue; sum += data[i]; System.out.println("Sum: " + sum); % java SumNumsSkip sum = 23 32
Mathematical Induction Base Case Inductive Step Recursion vs. Repetition CSCI 136: Fundamentals of Computer Science II, Spring 2016 33
Prove a statement involving an integer N Base case: Prove it for small N (usually 0 or 1) Induction step: Assume true for size N-1 Prove it is true for size N 34
Prove a statement involving an integer N Base case: Prove it for small N (usually 0 or 1) Induction step: Assume true for size N-1 Prove it is true for size N Example: Prove T(N) = 1 + 2 + 3 +... + N = N(N + 1) / 2 for all N 35
Prove a statement involving an integer N Base case: Prove it for small N (usually 0 or 1) Induction step: Assume true for size N-1 Prove it is true for size N Example: Prove T(N) = 1 + 2 + 3 +... + N = N(N + 1) / 2 for all N Base case: T(1) = 1 = 1(1 + 1) / 2 36
Example: Prove T(N) = 1 + 2 + 3 +... + N = N(N + 1) / 2 for all N Base case: T(1) = 1 = 1(1 + 1) / 2 Induction step: Assume true for size N 1: 1 + 2 +... + N-1 = T(N - 1) = (N - 1)(N) / 2 T(N) = 1 + 2 + 3 +... + N-1 + N = (N 1)(N) / 2 + N = (N 1)(N) / 2 + 2N / 2 = (N 1 + 2)(N) / 2 = (N + 1)(N) / 2 37
Goal: Compute factorial N! = 1 * 2 * 3... * N N! = 1 for N=0 = (N-1)!*N otherwise Base case: 0! = 1 Induction step: Use (N 1)! to find N! public static long fact(long N) if (N == 0) return 1; return fact(n - 1) * N; 4! = 4 * 3 * 2 * 1 = 24 4! = 4 * 3! 3! = 3 * 2! 2! = 2 * 1! 1! = 1 * 0! 0! = 1 base case induction step public static void main(string [] args) int N = Integer.parseInt(args[0]); System.out.println(N + "! = " + fact(n)); 38
public static long fact(long N) System.out.println("start, fact " + N); if (N == 0) System.out.println("end base, fact " + N); return 1; long step = fact(n - 1); System.out.println("end, fact " + N ); return step * N; start, fact 4 start, fact 3 start, fact 2 start, fact 1 start, fact 0 end base, fact 0 end, fact 1 end, fact 2 end, fact 3 end, fact 4 4! = 24 5 levels of fact() 39
Recursive algorithms also have an iterative version public static long fact(long N) if (N == 0) return 1; return fact(n - 1) * N; Recursive algorithm public static long fact(long N) long result = 1; for (int i = 1; i <= N; i++) result *= i; return result; Iterative algorithm Reasons to use recursion: Code is more compact and easier to understand Easer to reason about correctness Reasons not to use recursion: If you end up recalculating things repeatedly Processor with very little memory (e.g. 8051 = 128 bytes) 40
Missing base case public static long fact(long N) return fact(n - 1) * N; No convergence guarantee public static double badidea(int N) if (N == 1) return 1.0; return badidea(1 + N/2) + 1.0/N; % java Factorial 5 Exception in thread "main" java.lang.stackoverflowerror at Factorial.fact(Factorial.java:8) at Factorial.fact(Factorial.java:8) at Factorial.fact(Factorial.java:8) at Factorial.fact(Factorial.java:8) at Factorial.fact(Factorial.java:8) at Factorial.fact(Factorial.java:8) at Factorial.fact(Factorial.java:8) at Factorial.fact(Factorial.java:8) at Factorial.fact(Factorial.java:8)... Both result in infinite recursion = stack overflow 41
Recursion: Brownian Landscape 42
Review of Java Basics Data Types Arrays NEW: multidimensional arrays Boolean Expressions Conditionals: if-else NEW: switch Iteration: while and for loops NEW: alternate for loop syntax NEW: break and continue Recursion CSCI 136: Fundamentals of Computer Science II, Spring 2016 43