Michele Van Dyne Museum 204B CSCI 136: Fundamentals of Computer Science II, Spring

Similar documents
Other conditional and loop constructs. Fundamentals of Computer Science Keith Vertanen

Recursion CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2011

Recursion. Fundamentals of Computer Science

Recursion. Overview. Mathematical induction. Hello recursion. Recursion. Example applications. Goal: Compute factorial N! = 1 * 2 * 3...

Variables and data types

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

MODULE 02: BASIC COMPUTATION IN JAVA

Built-in data types. logical AND logical OR logical NOT &&! public static void main(string [] args)

Built-in data types. public static void main(string [] args) logical AND logical OR logical NOT &&! Fundamentals of Computer Science

Enumerations. Fundamentals of Computer Science

Java Review. Fundamentals of Computer Science

Conditionals, Loops, and Style

DATA TYPES AND EXPRESSIONS

Conditionals, Loops, and Style. Control flow thus far. if statement. Control flow. Common branching statement Evaluate a boolean expression

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Cellular Automata Language (CAL) Language Reference Manual

Repetition Structures

Condi(onals and Loops

Topic 5: Enumerated Types and Switch Statements

Computer Programming I - Unit 5 Lecture page 1 of 14

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

Pace University. Fundamental Concepts of CS121 1

CS 61B Data Structures and Programming Methodology. June David Sun

Introduction to Programming Using Java (98-388)

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

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Full file at

Avoiding magic numbers

CONDITIONAL EXECUTION

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Loops. CSE 114, Computer Science 1 Stony Brook University

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

Unit 2: Java in the small. Prepared by: Dr. Abdallah Mohamed, AOU-KW

School of Computer Science CPS109 Course Notes 6 Alexander Ferworn Updated Fall 15. CPS109 Course Notes 6. Alexander Ferworn

1.3 Conditionals and Loops

Introduction to the Java Basics: Control Flow Statements

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

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

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Instructor: SIR MUHAMMAD NAVEED Created by: ARSLAN AHMED SHAAD ( ) MUHAMMAD BILAL ( ) ISIT:

Unit 2: Java in the small

} Evaluate the following expressions: 1. int x = 5 / 2 + 2; 2. int x = / 2; 3. int x = 5 / ; 4. double x = 5 / 2.

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

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

Java is an objet-oriented programming language providing features that support

Repetition, Looping. While Loop

CS 231 Data Structures and Algorithms, Fall 2016

Introduction. C provides two styles of flow control:

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

REPETITION CONTROL STRUCTURE LOGO

Le L c e t c ur u e e 3 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Control Statements

22c:111 Programming Language Concepts. Fall Types I

Lecture 12. Data Types and Strings

Boolean Data-Type. Boolean Data Type (false, true) i.e. 3/6/2018. The type bool is also described as being an integer: bool bflag; bflag = true;

GridLang: Grid Based Game Development Language Language Reference Manual. Programming Language and Translators - Spring 2017 Prof.

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

1.3 Conditionals and Loops. 1.3 Conditionals and Loops. Conditionals and Loops

Programming for Engineers Iteration

Lesson 06 Arrays. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

AP Programming - Chapter 6 Lecture

CS313D: ADVANCED PROGRAMMING LANGUAGE

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Following is the general form of a typical decision making structure found in most of the programming languages:

CSI33 Data Structures

Mul$dimensional arrays. CSCI 136: Fundamentals of Computer Science II Keith Vertanen

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

1.3 Conditionals and Loops

CSE115 / CSE503 Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall Office hours:

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

The Warhol Language Reference Manual

Objectives. Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments

Mul$- state systems CSCI 255: Introduc/on to Embedded Systems Keith Vertanen Copyright 2011

COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015

STUDENT LESSON A12 Iterations

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

Repetition CSC 121 Fall 2014 Howard Rosenthal

CHAPTER : 9 FLOW OF CONTROL

CS 112 Introduction to Programming

2.3 Recursion. Overview. Mathematical Induction. What is recursion? When one function calls itself directly or indirectly.

CHAPTER 5 FLOW OF CONTROL

1/16/12. CS 112 Introduction to Programming. A Foundation for Programming. (Spring 2012) Lecture #4: Built-in Types of Data. The Computer s View

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

More Programming Constructs -- Introduction

CONDITIONAL EXECUTION

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

What did we talk about last time? Examples switch statements

Zheng-Liang Lu Java Programming 45 / 79

Chapter 7. Iteration. 7.1 Multiple assignment

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

Topic 4 Expressions and variables

Computer Programming, I. Laboratory Manual. Experiment #3. Selections

FORM 2 (Please put your name and form # on the scantron!!!!)

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.


Two Types of Types. Primitive Types in Java. Using Primitive Variables. Class #07: Java Primitives. Integer types.

Transcription:

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