Week 7 CS 302 Jim Williams.

Slides:



Advertisements
Similar presentations
Topic 10 Java Memory Management. 1-2 Memory Allocation in Java When a program is being executed, separate areas of memory are allocated for each class.
Advertisements

Recursion –a programming strategy for solving large problems –Think “divide and conquer” –Solve large problem by splitting into smaller problems of same.
Fundamentals of Computer Science Lecture 14: Recursion Instructor: Evan Korth New York University.
Unit 181 Recursion Definition Recursive Methods Example 1 How does Recursion work? Example 2 Problems with Recursion Infinite Recursion Exercises.
1 CSCD 300 Data Structures Recursion. 2 Proof by Induction Introduction only - topic will be covered in detail in CS 320 Prove: N   i = N ( N + 1.
Warm-Up: April 21 Write a loop (type of your choosing) that prints every 3 rd number between 10 and 50.
CSE 12 – Basic Data Structures Cynthia Bailey Lee Some slides and figures adapted from Paul Kube’s CSE 12 CS2 in Java Peer Instruction Materials by Cynthia.
Recursion. Math Review Given the following sequence: a 1 = 1 a n = 2*a n-1 OR a n+1 = 2*a n What are the values of the following? a 2 = a 3 = a 4 =
 Prentice Hall. All rights reserved. 1 CS 1120 – Computer Science II Recursion (Ch.15) Many slides modified by Prof. L. Lilien (even many without.
Java Basics Hussein Suleman March 2007 UCT Department of Computer Science Computer Science 1015F.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
1 Recursion Recursive definitions Recursive methods Run-time stack & activation records => Read section 2.3.
CSE 110 Review Session Hans Hovanitz, Kate Kincade, and Ian Nall.
Review :chapters What is an algorithm? A step by step description of how to accomplish a task. For example, Adding 3 numbers N1, N2 and N3 Add.
Programming With Java ICS201 University Of Ha’il1 Chapter 11 Recursion.
CS1101: Programming Methodology Preparing for Practical Exam (PE)
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
A 2-D Array is a structure that storage space both vertically and horizontally. Thus, the array has both rows and columns. 2-D Arrays are used to create.
Values vs. References Lecture 13.
Java Memory Management
CprE 185: Intro to Problem Solving (using C)
Introduction to Recursion
Java Memory Management
Chapter 6 More Conditionals and Loops
CS Week 14 Jim Williams, PhD.
CS Week 2 Jim Williams, PhD.
CS 200 Arrays, Loops and Methods
CS 302 Week 15 Jim Williams, PhD.
CS 200 Branches Jim Williams, PhD.
CS Week 4 Jim Williams, PhD.
CS Week 11 Jim Williams, PhD.
CS Week 13 Jim Williams, PhD.
CS 302 Week 10 Jim Williams.
CS Week 8 Jim Williams, PhD.
Recursion Recursive Thinking Recursive Programming
CS 200 Using Objects Jim Williams, PhD.
CS Week 6 Jim Williams, PhD.
CS Week 7 Jim Williams, PhD.
CS 200 Arrays, Loops and Methods
CS 1110 Final Exam: Review Session 1 Drawing frames for calls, executing method calls Biggest issue!!! You can’t do questions on this topic correctly.
CS 302 Week 8 Jim Williams, PhD.
CS Week 9 Jim Williams, PhD.
Week 6 CS 302 Jim Williams, PhD.
CS 200 Objects and ArrayList
Recursion Recursion is a math and programming tool
Fundamentals 2.
CS 200 More Primitives, Objects, Branches and Methods
Recursion.
CS 200 Loops Jim Williams, PhD.
CS 200 Additional Topics and Review
CS 1110 Final Exam: Review Session 1 Drawing frames for calls, executing method calls Biggest issue!!! You can’t do questions on this topic correctly.
CS 200 Primitives and Expressions
CS 200 Arrays Jim Williams, PhD.
CS Week 4 Jim Williams, PhD.
Stacks.
CS 200 Primitives and Expressions
Module 1-10: Recursion.
CS 200 Additional Topics and Review
CS 200 Methods, Using Objects
CS 200 Objects and ArrayList
Java Programming: Chapter 9: Recursion Second Edition
Dr. Sampath Jayarathna Cal Poly Pomona
ICS103 Programming in C Lecture 11: Recursive Functions
CS Week 3 Jim Williams, PhD.
CS 200 Objects and ArrayList
First Semester Review.
CS302 Week 6 Jim Williams.
CS 200 Additional Topics and Review
Chapter 6: Methods CS1: Java Programming Colorado State University
Presentation transcript:

Week 7 CS 302 Jim Williams

This Week Lab: Static Methods P2: Milestone 1, Partners due Thursday P1 Feedback regrade requests Exam 1 results review, discuss

Lecture More methods multiple files Constants static memory area Debugging exam review

What is print out? two one two main main two one two two two one main one two two main static void one() { System.out.print( "one "); } static void two(int num) { System.out.print("two "); one(); public static void main( String []args) { two( 3); System.out.print("main "); try it.

What do a and b have in common? public static void main(String []args) { mA(); mB(); } static void mA() { int a = 10; static void mB() { int b; System.out.println( b); may be the exact same memory location looking at b will reveal a (unintentially) nothing Error A is the best answer. This example is typically discussed with a memory diagram intended to illustrate how local variables are allocated on the stack. Local variables are a part of the stack frame that are allocated when a method is called and discarded when the method ends. Since mA() has 1 int variable allocated (pushed on stack) and then discarded (popped off stack) then mB() can reuse that same memory area. Thinking through this possibility is intended to help develop a deep understanding of local variables.

Constants

static Memory area

What is the value of num? num: 10 Stuff.num: 6 Stuff.num: 10 class Stuff { final static int MAX_VALUE = 10; //allowed static int num = 6; //NOT allowed in P2 static void change( int n) { num = n + 1; } public static void main( String [] args) { int num = MAX_VALUE; change( num); System.out.println("num:" + num); System.out.println("Stuff.num:" + Stuff.num); num: 10 Stuff.num: 6 Stuff.num: 10 Stuff.num: 11 error

What are values of x and y? static int x; static int y = 2; static int methodA( int y) { x = y + 1; return x + y; } public static void main(String []args) { int x = 5; y = methodA( x); System.out.println("x="+x+ " y="+y); x=5 y=11 x=3 y=2 x=5 y=2 x=3 y=11

Instance methods

What is print out? ling Future lin error String str = "Falling Off a Cliff " + "by Eileen Dover"; System.out.println( str.substring(3,6)); String str2 = "The Future of Robotics " + " by Cy Borg and Anne Droid"; System.out.println( str2.substring( str2.indexOf('e') + 1, str2.indexOf('o')).trim()); try it Strings courtesy of Boy Scouts

What kind of methods? max: class nextInt: instance Math.max( 10, 20); max: instance nextInt: class Math.max( 10, 20); Random randGen = new Random(); randGen.nextInt( 5); class methods (static) instance methods (non-static) A is the best answer

Instance vs. Class (static) Methods method definition has “static” modifier use name of class when calling Math.max( 10, 20); Instance (non-static) Methods method definition does Not have “static” modifier use instance of class when calling Random randGen = new Random(); randGen.nextInt( 5);

Where is memory allocated? name: heap new String("fido"): heap name: stack new String("fido"): stack public static void main( String []args) { String name; new String("fido"); name = new String("spot"); } B is the best answer A, C and D are not true

Debugging with Print statements See what is going on. Divide and conquer. import java.util.Scanner; public class Factorial { public static int factorial(int n) { int result = 1; while( n-- > 0) { result *= n; } return result; public static void main( String []args) { Scanner scnr = new Scanner( System.in); System.out.print("Find factorial of what number? "); int num = scnr.nextInt(); int factorial = factorial( num); System.out.println( "The factorial of " + num + " is " + factorial); scnr.close(); //////////////////////////////////////////////////////////////////////////////// // Title: PascalTriangle // Files: PascalTriangle.java // // Author: Zhicheng Gu // Email: zhichenggu@cs.wisc.edu /////////////////////////////// 80 COLUMNS WIDE /////////////////////////////// import java.util.Arrays; /** * This class is used to print first five rows of Pascal's Triangle. https://en.wikipedia.org/wiki/Pascal%27s_triangle * The output of this class(without bugs) should be: * * 1 * 1 1 * 1 2 1 * 1 3 3 1 * 1 4 6 4 1 * * @author Zhicheng Gu * */ public class PascalTriangle { // The number of rows we want to print. private static final int MAX_LEVEL = 5; /** * * Main class will first initialize and print 'nums' array, * which contains first row of Pascal's Triangle. * Then it will get and print numbers of next level iteratively. * * @param args : not used. */ public static void main(String[] args) { // Array stores numbers on each level. // Numbers on tree levels are mapping to the smallest array indexes. // For example, for the first three rows, // nums should be: [1, 0, 0, 0, 0], [1, 1, 0, 0, 0], [1, 2, 1, 0, 0]. int[] nums = new int[MAX_LEVEL]; nums[0] = 1; // Get and print the numbers on each level. for (int level = 1; level <= MAX_LEVEL; level++) { if (level > 1) { getNextLevel(nums, level); } // TODO: Part 1. Use print to help you debug. // This print statement helps determine whether the problem is in // getNextLevel or printOneLevel. // System.out.println("Main method, nums: " + Arrays.toString(nums)); printOneLevel(nums, level); } } /** * This method is used to print one level of Pascal's Triangle. * * @param nums : Array stores numbers. * @param level : The current level. */ private static void printOneLevel(int[] nums, int level) { // Print the spaces at the beginning of each line. for (int i = 0; i < MAX_LEVEL - level; i++) { System.out.print(' '); } for (int i = 0; i < level; i ++) { System.out.print(nums[i] + " "); } System.out.println(); } /** * This method is used to calculate numbers on next level * based on current level. * * @param nums : Array stores numbers. * @param nextLevel : The number of next level. */ private static void getNextLevel(int[] nums, int nextLevel) { int[] nextNums = new int[MAX_LEVEL]; // Array stores numbers on next level. nextNums[0] = nums[0]; // Each number at position i on the next level equals to the sum of // number at position i and i - 1 on the current level, // except the first one and the last one. for (int i = 1; i < nextLevel - 1; i++) { nextNums[i] = nums[i - 1] + nums[i]; } nextNums[nextLevel - 1] = nums[nextLevel - 2]; // TODO: Part 2. Use print to help you debug. // With the print statement in main we figured out the problem must be in this method. // This print statement is to see if this method is working correctly to this point. // System.out.println("getNextLevel method, nextNums: " + Arrays.toString(nextNums)); nums = nextNums; } }

Recall Fibonacci Sequence 1 1 2 3 5 8 13 21 … Each is the sum of the previous 2. https://en.wikipedia.org/wiki/Fibonacci_number

Iterative solution public static void main(String[] args) { int n = 10; int [] fib = new int[n]; fib[0] = 1; fib[1] = 1; for (int i = 2; i < n; i++) { fib[i] = fib[i-1] + fib[i-2]; } System.out.println("fib "+n+"= " + fib[n-1]); {

How many times is fib method called? 1 3 9 Error static int fib(int num) { if ( num <= 1) return 1; else return fib( num -1) + fib( num -2); } public static void main(String[] args) { System.out.println("fibonacci 4: " + fib(4)); try it.