CT 229 Methods Continued

Similar documents
CT 229 Arrays Continued

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

CT 229 Java Syntax Continued

CT 229 Java Syntax Continued

News and information! Review: Java Programs! Feedback after Lecture 2! Dead-lines for the first two lab assignment have been posted.!

Lecture 5: Methods CS2301

(A) 99 (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution

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

Lecture 05: Methods. AITI Nigeria Summer 2012 University of Lagos.

CS171:Introduction to Computer Science II

(A) 99 ** (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution

CS Week 2. Jim Williams, PhD

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

Java Review. Java Program Structure // comments about the class public class MyProgram { Variables

CS111: PROGRAMMING LANGUAGE II

Methods and Functions

CS111: PROGRAMMING LANGUAGE II

AP Computer Science Unit 1. Programs

1007 Imperative Programming Part II

COMP 202 Recursion. CONTENTS: Recursion. COMP Recursion 1

Announcements. PS 3 is due Thursday, 10/6. Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am

CS110D: PROGRAMMING LANGUAGE I

i.e.: n! = n (n 1)

Opening Problem. Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Introduction to Programming Using Java (98-388)

Discover how to get up and running with the Java Development Environment and with the Eclipse IDE to create Java programs.

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

Methods. Bok, Jong Soon

Opening Problem. Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.

Tutorials. Inf1-OP. Learning Outcomes for this week. A Foundation for Programming. Conditionals and Loops 1

Computer Programming: C++

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

Every language has its own scoping rules. For example, what is the scope of variable j in this Java program?

Chapter 12 Supplement: Recursion with Java 1.5. Mr. Dave Clausen La Cañada High School

CT 229. Java Syntax 26/09/2006 CT229

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS11 Java. Fall Lecture 1

Object-Oriented Programming

RECURSION. Data Structures & SWU Rachel Cardell- Oliver

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

AP CS Unit 3: Control Structures Notes

Decision-Making and Repetition

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

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

1 Shyam sir JAVA Notes

Chapter 5 Methods. public class FirstMethod { public static void main(string[] args) { double x= -2.0, y; for (int i = 1; i <= 5; i++ ) { y = f( x );

EK131 E5 Introduction to Engineering

More types, Methods, Conditionals. ARCS Lab.

Encapsulation. You can take one of two views of an object: internal - the structure of its data, the algorithms used by its methods

A Foundation for Programming

JVM (java) compiler. A Java program is either a library of static methods (functions) or a data type definition

Chapter 5: Methods. by Tony Gaddis. Starting Out with Java: From Control Structures through Objects. Fourth Edition

CMSC 150 LECTURE 7 RECURSION

Introduction to Software Development (ISD) Week 3

Loops. CSE 114, Computer Science 1 Stony Brook University

Chapter 4 Defining Classes I

Methods. CSE 114, Computer Science 1 Stony Brook University

CP122 CS I. Chapter 13: Recursion

Recursion Chapter 17. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Building Java Programs

Week 6 CS 302. Jim Williams, PhD

COMP-202. Objects, Part III. COMP Objects Part III, 2013 Jörg Kienzle and others

Conversions and Overloading : Overloading

CT 229 Fundamentals of Java Syntax

CT 229 Arrays in Java

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

CS 11 java track: lecture 1

34. Recursion. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Pace University. Fundamental Concepts of CS121 1

Selected Questions from by Nageshwara Rao

Functions. x y z. f (x, y, z) Take in input arguments (zero or more) Perform some computation - May have side-effects (such as drawing)

CS 302 Week 9. Jim Williams

Name EID. (calc (parse '{+ {with {x {+ 5 5}} {with {y {- x 3}} {+ y y} } } z } ) )

University of Palestine. Mid Exam Total Grade: 100

Computer Science II Lecture 1 Introduction and Background

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

Data Structure and Programming Languages

Variables, Types, Operations on Numbers

Arrays. Outline 1/7/2011. Arrays. Arrays are objects that help us organize large amounts of information. Chapter 7 focuses on:

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

Building Java Programs

There are some situations in which recursion can be massively inefficient. For example, the standard Fibonacci recursion Fib(n) = Fib(n-1) + Fib(n-2)

Fundamentals of Programming & Procedural Programming

Constants. Why Use Constants? main Method Arguments. CS256 Computer Science I Kevin Sahr, PhD. Lecture 25: Miscellaneous

Notes - Recursion. A geeky definition of recursion is as follows: Recursion see Recursion.

CS 231 Data Structures and Algorithms, Fall 2016

PROGRAMMING FUNDAMENTALS

M e t h o d s a n d P a r a m e t e r s

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

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

CSC 148 Lecture 3. Dynamic Typing, Scoping, and Namespaces. Recursion

CSCI 136 Data Structures & Advanced Programming. Fall 2018 Instructors Bill Lenhart & Bill Jannen

Example: Monte Carlo Simulation 1

Building Java Programs

Chapter 2: Data and Expressions

Administration. Conditional Statements. Agenda. Syntax. Flow of control. Lab 2 due now on floppy Lab 3 due tomorrow via FTP

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

Transcription:

CT 229 Methods Continued 13/10/2006 CT229

Lab Assignments Due Date for current lab assignment : Oct 20 th In Part 1 of Assignment you can declare a constant 3.14 to use as PI or you can use Math.PI Formula for converting from Celsius to Fahrenheit F = 9/5 (C+32) Before submission make sure that the name of each.java file matches the name given in the assignment sheet!!!! Remember: Electronic Submission @ http://ecrg-vlab01.it.nuigalway.ie/uploader/submissions.html 13/10/2006 CT229 1

Review of Last Week- Loops Loops While Loops Do/While Loops For Loops Different methods for initialising and incrementing the control variable in a for loop Nested For Loops 13/10/2006 CT229 2

Review of Last Week- Methods Format: method-type return-type method-name (parameter-list) declarations and statements: body of method Passing Parameters Returning a Value from a Method Scope of Variables in a Method 13/10/2006 CT229 3

More About Parameters When a variable is an argument in calling a method: The argument variable does not have to have the same name as the corresponding parameter! The parameter in the same position is given the value of the argument variable Simple variables are passed by value: the method just gets a copy of the value; they are not made equivalent If you change the value in the method, the original value of the variable is not changed int n = 5; public static void noeffect(int x) noeffect(n); System.out.println ("n is now " + n); x = x * 3; // Prints: n is now 5 // HAS NO EFFECT! 13/10/2006 CT229 4

Example of Variable Scope public static void main(string[] args) int num = 5; Value of num is 6 Value of num is 5 printoutvalues(num); System.out.println("Value of num is "+num); public static void printoutvalues(int num) num++; System.out.println("Value of num is "+num); 13/10/2006 CT229 5

Return Values Methods must return a value of the appropriate type Unless declared to be void Done with a return statement Often last statement in method, but can occur anywhere Can have multiple return statements Same rules as for parameters: For primitive data types, a value is returned The value returned may be used in an assignment or other expression in the calling method 13/10/2006 CT229 6

Introduction to Overloading Problem Scenario Consider a simple method that prints out a textual representation of its argument. This method should be able to print out an int, double, boolean or String. You could create four separate methods public static void printint(int num) public static void printdouble(double num), public static void printboolean(boolean condition) public static void printstring(string words) However now a user has to remember the name of each method when they want to print out a value. It would be much easier from a users perspective to call a single method (println) that would print out whatever value you pass it (whether it be an int, double, boolean or String) 13/10/2006 CT229 7

Introduction to Overloading int intnum = 2; double doublenum = 2.3; boolean test = true; String sample = "Hello World"; System.out.println(intNum); System.out.println(doubleNum); System.out.println(test); System.out.println(sample); 2 2.3 true Hello World Notice that the method println is capable of taking in an int parameter, a double parameter, a boolean parameter and a String parameter!!!! 13/10/2006 CT229 8

Overloading (1) Sometimes, you need methods that perform similar operations for different data types would like to use the same name e.g. println(int) / println(float) / println(string) Method Overloading: Java allows different methods of the same name to be defined, as long as they have different parameter lists The signature of each method must be unique Method Signature: Name of method + data types of parameters, in given order: fn(int) / fn(float) / fn(int, String) 13/10/2006 CT229 9

Example of Overloading public static void main(string[] args) double doublenum = 5.2; int intnum = 6; System.out.println( triple( doublenum ) ); System.out.println( triple( intnum) ); public static int triple(int num) return (num *= 3); 15.6 18 public static double triple(double num) Also See: Overloading.java return (num *= 3); 13/10/2006 CT229 10

Overloading (2) Basic principle: The compiler must be able to determine unambiguously which version of method to call Return value not considered: you cannot define two methods that differ only in return value Names of parameters not considered: Compiler could not determine from method call which one is intended 13/10/2006 CT229 11

Recursion Methods can call other methods, but can also call themselves Directly; or indirectly via another method This creates a form of loop: termed recursion Like other loops, recursive methods have to be carefully constructed so that they terminate correctly A small but significant number of problems can be solved elegantly this way 13/10/2006 CT229 12

Recursion MethodA MethodA MethodA MethodA 13/10/2006 CT229 13

Recursion Problem You probably see one problem with recursion. Where does it end? When you write recursive methods you have to be careful to include stopping conditions. This is called a base condition Although Java doesn't put any particular limits on the depth to which you can expand a recursion, it is very possible to have a run-away recursion eat up all the memory in your computer. 13/10/2006 CT229 14

Recursion A recursive method must have: 1. Test to stop or continue the recursion 2. A base case that terminates the recursion 3. Recursive call(s) that continue the recursion 13/10/2006 CT229 15

Consider this Simple For Loop public static void main(string[] args) final int num1 =4; int total = 0; The total is 10 for (int i = num1; i > 0; i--) total += i; System.out.println("Total is "+10); 13/10/2006 CT229 16

Easiest Recursion Program Ever!! public static void main(string[] args) int num = 4; int total = summation(num); System.out.println("Total is "+total); The total is 10 public static int summation(int num) if (num == 1) Test Base Case else return 1; return ( num + summation(num-1) ); Recursive Call 13/10/2006 CT229 17

Solving Factorial using Recursion Consider the following example Facorial (!) 5! = 5 * 4 * 3 * 2 * 1 How would you implement this using a recursion?? 13/10/2006 CT229 18

Factorial using Recursion factorial( 5 ) = 5 * factorial( 4 ) = 5 * ( 4 * factorial( 3 ) ) = 5 * ( 4 * (3 * factorial( 2 ) ) ) = 5 * ( 4 * (3 * (2 * factorial( 1 ) ) ) ) = 5 * ( 4 * (3 * (2 * ( 1 * factorial( 0 ) ) ) ) ) = 5 * ( 4 * (3 * (2 * ( 1 * 1 ) ) ) ) = 5 * 4 * 3 * 2 * 1 * 1 = 120 13/10/2006 CT229 19

Recursive Factorial This can be summed up as N! = N * (N-1)! Assume factorial is the name of the method we will use in our java program factorial( N ) = N * factorial( N-1 ) How should it end (Base Case)? factorial(0) = 1 13/10/2006 CT229 20

Recursive Factorial public static int factorial( int num ) if ( num == 0 ) return 1; else return num * factorial(num -1) ; 13/10/2006 CT229 21

Recursion Another Example: Fibonacci numbers for a mathematical sequence that can be defined recursively as: See: Fibonacci.java => 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233. Notice after two starting values, each number is the sum of the two preceding numbers 13/10/2006 CT229 22

Recursive Fibonacci public static int fibonacci(int n) if (n == 0) return 0; else if (n == 1) return 1; else return fibonacci(n-1) + fibonacci(n-2); 13/10/2006 CT229 23

Fibonacci 13/10/2006 CT229 24

Recursion (2) Iteration can be used anywhere you can use recursion Sometimes recursion is more elegant, if it reflects the way the problem is usually thought about Aim to use most intuitive representation of problems public static int factorial( int num) int product = 1; for ( int j=1; j<=num; j++ ) product *= j; return product; 13/10/2006 CT229 25

Drawbacks of Recursion Drawbacks of recursion: Inefficient use of resources: large amount of deeply nested method calls to be kept track of together Number of calls can explode: f(20) takes 21,891 calls to method f(30) takes 2,692,537 calls Depending on algorithm, can involve re-computing values that were already computed Normal loops can avoid these problems 13/10/2006 CT229 26