A Foundation for Programming

Similar documents
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)

Lecture 5: Methods CS2301

2.1 Functions. f (x, y, z)

CS110D: PROGRAMMING LANGUAGE I

CS 112 Introduction to Programming

Introduction to Programming Using Java (98-388)

Functions (or Static Methods) (Spring 2012)

2.1 Functions. 2.1 Functions. A Foundation for Programming. Functions (Static Methods) x y. f (x, y, z)

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

Functions / Static Methods. Inf1-OP. What s this static method business? Functions / Static Methods. Haskell function: type declaration

Inf1-OOP. Functions aka Static Methods. Perdita Stevens, adapting earlier version by Ewan Klein. January 11, School of Informatics

CS110: PROGRAMMING LANGUAGE I

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

CSCI 135 Exam #0 Fundamentals of Computer Science I Fall 2013

CLASSES AND OBJECTS. Fundamentals of Computer Science I

Chapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Static methods. Not actually a valid Java static method. Fundamentals of Computer Science Keith Vertanen

DATA TYPES AND EXPRESSIONS

McGill University School of Computer Science COMP-202A Introduction to Computing 1

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 );

2.1 Functions. x y. f (x, y, z) A Foundation for Programming. Functions (Static Methods)

Lecture #6-7 Methods

Chapter 5 Methods. Modifier returnvaluetype methodname(list of parameters) { // method body; }

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

All classes in a package can be imported by using only one import statement. If the postcondition of a method is not met, blame its implementer

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

AP CS Unit 3: Control Structures Notes

Chapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

CIS 110 Introduction To Computer Programming. February 29, 2012 Midterm

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

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

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

To define methods, invoke methods, and pass arguments to a method ( ). To develop reusable code that is modular, easy-toread, easy-to-debug,

COMP-202: Foundations of Programming. Lecture 4: Methods Jackie Cheung, Winter 2016

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

2.1, 2.2 Functions and Libraries

Introduction to Computer Science Unit 2. Notes

A foundation for programming. Classes and objects. Overview. Java primitive types. Primitive types Creating your own data types

CS-201 Introduction to Programming with Java

CS115 Principles of Computer Science

CS171:Introduction to Computer Science II

Java Methods. Lecture 8 COP 3252 Summer May 23, 2017

Introduction to Computer Science Unit 2. Notes

Object Oriented Methods : Deeper Look Lecture Three

Condi(onals and Loops

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018

CS 112 Introduction to Programming

Activity 4: Methods. Content Learning Objectives. Process Skill Goals

The life and death of objects, sta2cs. CSCI 136: Fundamentals of Computer Science II Keith Vertanen

More About Objects and Methods

Methods. CSE 114, Computer Science 1 Stony Brook University

CS 112 Introduction to Programming

Programming Language Concepts: Lecture 2

Zheng-Liang Lu Java Programming 45 / 79

Inheritance and Polymorphism

CONDITIONAL EXECUTION

EECS1710. Announcements. Labtests have been returned Term Test #01 marking is in progress. Next Labtest: Thu Oct 23/Fri Oct 24

Object Oriented Programming in C#

Chapter 5 Methods / Functions

CLASSES AND OBJECTS. Fundamentals of Computer Science I

COS 126 Midterm 1 Written Exam Fall 2011

Loops. CSE 114, Computer Science 1 Stony Brook University

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

Recap: Structure of a Java program CS 112 Introduction to Programming. A Foundation for Programming Why Introduce Static Methods?

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

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

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

1.3 Conditionals and Loops

int a; int b = 3; for (a = 0; a < 8 b < 20; a++) {a = a + b; b = b + a;}

Chapter 6 Methods. Dr. Hikmat Jaber

Lec 7. for loops and methods

COP3502 Programming Fundamentals for CIS Majors 1. Instructor: Parisa Rashidi

Lec 3. Compilers, Debugging, Hello World, and Variables

Inf1-OP. Functions aka Static Methods. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. School of Informatics

CS-201 Introduction to Programming with Java

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

MODULE 02: BASIC COMPUTATION IN JAVA

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

Lecture Set 4: More About Methods and More About Operators

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

1.1 Your First Program

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

CSCI 135 Exam #0 Fundamentals of Computer Science I Fall 2012

Chapter 5 Methods. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

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

Lecture 04 FUNCTIONS AND ARRAYS

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

JAVA Programming Concepts

LAB 13: ARRAYS (ONE DIMINSION)

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

COMP-202: Foundations of Programming. Lecture 5: Arrays, Reference Type, and Methods Sandeep Manjanna, Summer 2015

Java Fundamentals (II)

Methods CSC 121 Spring 2017 Howard Rosenthal

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

CS1150 Principles of Computer Science Loops (Part II)

CSCI 135 Midterm Fundamentals of Computer Science I Fall 2011

Transcription:

2.1 Functions

A Foundation for Programming any program you might want to write objects functions and modules build bigger programs and reuse code graphics, sound, and image I/O arrays conditionals and loops Math primitive data types text I/O assignment statements 2

Functions Take in input arguments (zero or more) Perform some computation May have side-effects (such as drawing) Return one output value Input Arguments x y z Return Value f f (x, y, z)

Functions (Static Methods) Applications: Use mathematical functions to calculate formulas Use functions to build modular programs Examples: Built-in functions:,, Math.random() Math.abs() Integer.parseInt() These methods return, respectively, a double, double, and int value. I/O libraries: PennDraw.circle(x,y,halfRadius), PennDraw.line(x0,y0,x1,y1) User-defined functions: main() 4

Why do we need functions? Break code down into logical sub-steps Readability of the code improves Testability - focus on getting each individual function correct 5

Anatomy of a Java Function Java functions It is easy to write your own Example: double sqrt(double c) 2.0 input sqrt(c) = c return type output method name 1.414213 arguments public static double sqrt(double c) {... method signature (excludes return type) Please note that the method signature is defined incorrectly in the figure on pg 188 of your textbook 6

Anatomy of a Java Function Java functions It is easy to write your own Example: double sqrt(double c) 2.0 input sqrt(c) = c output 1.414213 public static double sqrt(double c) 7

Flow of Control Functions provide a new way to control the flow of execution implicit return statement at end of void function 8

Flow of Control What happens when a function is called: Control transfers to the function Argument variables are assigned the values given in the call Function code is executed Return value is substituted in place of the function call in the calling code Control transfers back to the calling code Note: This is known as "pass by value" 9

Example Function to reverse a word Apply this word reversal function to reverse a sentence that is entered via command line arguments. Live coding time.. 10

Organizing Your Program Functions help you organize your program by breaking it down into a series of steps Each function represents some abstract step or calculation Arguments let you make the function have different behaviors Key Idea: write something ONCE as a function then reuse it many times 11

Scope Scope: the code that can refer to a particular variable A variable's scope is the entire code block (any any nested blocks) after its declaration Simple example: int count = 1; for (int i = 0; i < 10; i++) { count *= 2; // using 'i' here generates // a compiler error Best practice: declare variables to limit their scope 13

Function Challenge 1 Q. What happens when you compile and run the following code? public class Cubes1 { public static int cube(int i) { int j = i * i * i; return j; public static void main(string[] args) { int N = Integer.parseInt(args[0]); for (int i = 1; i <= N; i++) System.out.println(i + " " + cube(i)); 14

Scope with Functions 15

Tracing Functions public class Cubes1 { public static int cube(int i) { int j = i * i * i; return j; public static void main(string[] args) { int N = Integer.parseInt(args[0]); for (int i = 1; i <= N; i++) System.out.println(i + " " + cube(i)); % % 1 2 3 4 5 6 javac Cubes1.java java Cubes1 6 1 8 27 64 125 216 16

Last In First Out (LIFO) Stack of Plates

Method Overloading Two or more methods in the same class may also have the same name This is called method overloading 18

Method Signature A method is uniquely identified by its name and its parameter list (parameter types and their order) This is known as its signature Examples: static int min(int a, int b) static double min(double a, double b) static float min(float a, float b) 19

Return Type is Not Enough Suppose we attempt to create an overloaded circle(double x, double y, double r) method by using different return types: static void circle(double x, double y, double r) {... //returns true if circle is entirely onscreen, false otherwise static boolean circle(double x, double y, double r) {... This is NOT valid method overloading because the code that calls the function can ignore the return value circle(50, 50, 10); The compiler can t tell which circle() method to invoke Just because a method returns a value doesn t mean the calling code has to use it 20

Too Much of a Good Thing Automatic type promotion and overloading can sometimes interact in ways that confuse the compiler For example: // version 1 static void printaverage(int a, double b) {... // version 2 static void printaverage(double a, int b) {... Why might this be problematic? 21

Too Much of a Good Thing static void average(int a, double b) { /*code*/ static void average(double a, int b) { /*code*/ Consider if we do this public static void main (String[] args) {... average(4, 8);... The Java compiler can t decide whether to: promote 7 to 7.0 and invoke the first version of average(), or promote 5 to 5.0 and invoke the second version Take-home lesson: don t be too clever with method overloading 22

Function Examples overloading multiple arguments 28

Function Challenge 2 Q. What happens when you compile and run the following code? public class Cubes2 { public static int cube(int i) { int i = i * i * i; return i; public static void main(string[] args) { int N = Integer.parseInt(args[0]); for (int i = 1; i <= N; i++) System.out.println(i + " " + cube(i)); 29

Function Challenge 3 Q. What happens when you compile and run the following code? public class Cubes3 { public static int cube(int i) { i = i * i * i; public static void main(string[] args) { int N = Integer.parseInt(args[0]); for (int i = 1; i <= N; i++) System.out.println(i + " " + cube(i)); 30

Function Challenge 4 Q. What happens when you compile and run the following code? public class Cubes4 { public static int cube(int i) { i = i * i * i; return i; public static void main(string[] args) { int N = Integer.parseInt(args[0]); for (int i = 1; i <= N; i++) System.out.println(i + " " + cube(i)); 31

Function Challenge 5 Q. What happens when you compile and run the following code? public class Cubes5 { public static int cube(int i) { return i * i * i; public static void main(string[] args) { int N = Integer.parseInt(args[0]); for (int i = 1; i <= N; i++) System.out.println(i + " " + cube(i)); 32