CS 106 Introduction to Computer Science I

Similar documents
CS 106 Introduction to Computer Science I

CS 106 Introduction to Computer Science I

CS 106 Introduction to Computer Science I

CS 106 Introduction to Computer Science I

Static Methods. Why use methods?

CS 106 Introduction to Computer Science I

Lecture 5: Methods CS2301

Mobile App:IT. Methods & Classes

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

CS110D: PROGRAMMING LANGUAGE I

Lecture 04 FUNCTIONS AND ARRAYS

C Programming for Engineers Functions

Methods (Deitel chapter 6)

Methods (Deitel chapter 6)

CS 106 Introduction to Computer Science I

Introduction to Programming

CS 106 Introduction to Computer Science I

CS 106 Introduction to Computer Science I

Full file at

CS 106 Introduction to Computer Science I

Object Oriented Methods : Deeper Look Lecture Three

CS 251 Intermediate Programming Java Basics

CS1150 Principles of Computer Science Methods

CS11 Java. Fall Lecture 1

CS 206 Introduction to Computer Science II

Unit 7. Functions. Need of User Defined Functions

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

For example, when we first started Java programming we described the HelloWorld class:

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

Methods. Contents Anatomy of a Method How to design a Method Static methods Additional Reading. Anatomy of a Method

9 Working with the Java Class Library

CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU

Fundamentals of Programming Session 13

CSE 230 Intermediate Programming in C and C++ Functions

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

Chapter 5 - Methods Prentice Hall, Inc. All rights reserved.

CS 106 Introduction to Computer Science I

Arrays: Higher Dimensional Arrays. CS0007: Introduction to Computer Programming

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved.

CSc Introduction to Computing

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

CS 106 Introduction to Computer Science I

CS110: PROGRAMMING LANGUAGE I

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

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

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

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

Chapter 2: Data and Expressions

Primitive Data, Variables, and Expressions; Simple Conditional Execution

Declaration Syntax. Declarations. Declarators. Declaration Specifiers. Declaration Examples. Declaration Examples. Declarators include:

CS 106 Introduction to Computer Science I

Textbook. Topic 6: Functions. Motivation. What is a Function? What s a function? How can we use functions to write better software?

CS 231 Data Structures and Algorithms, Fall 2016

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

CS 106 Introduction to Computer Science I

Chapter 3 - Functions

CHAPTER 7 OBJECTS AND CLASSES

A Foundation for Programming

STUDENT LESSON A12 Iterations

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University

BM214E Object Oriented Programming Lecture 4

CSC Java Programming, Fall Java Data Types and Control Constructs

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #43. Multidimensional Arrays

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

C++ Programming Lecture 11 Functions Part I

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

Lecture 04 FUNCTIONS AND ARRAYS

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

Administration. Objects and Arrays. Objects. Agenda. What is an Object? What is a Class?

Module 10A Lecture - 20 What is a function? Why use functions Example: power (base, n)

CS-201 Introduction to Programming with Java

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

Defining Classes and Methods

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

Introduction to Computer Science Unit 2. Notes

Chapter 2: Data and Expressions

public class Foo { private int var; public int Method1() { // var accessible anywhere here } public int MethodN() {

CS 206 Introduction to Computer Science II

Programming Fundamentals for Engineers Functions. Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. Modular programming.

CS-201 Introduction to Programming with Java

APCS Semester #1 Final Exam Practice Problems

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

CIS133J. Working with Numbers in Java

Java Basic Programming Constructs

CS 206 Introduction to Computer Science II

CHAPTER 7 OBJECTS AND CLASSES

CS111: PROGRAMMING LANGUAGE II

Fundamentals of Programming Session 12

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

Topics. Chapter 5. Equality Operators

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University

Activity 6: Loops. Content Learning Objectives. Process Skill Goals

Introduction to Java Applications

ECE 122. Engineering Problem Solving with Java

Lesson 05 Methods. MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

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

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

PROGRAMMAZIONE I A.A. 2017/2018

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

CS 376b Computer Vision

Transcription:

CS 106 Introduction to Computer Science I 06 / 10 / 2015 Instructor: Michael Eckmann

Today s Topics Questions / comments? Method terminology and Programmer defined methods Michael Eckmann - Skidmore College - CS 106 - Summer 2015

what is a method A method is small piece of a program designed to achieve some specific task and usually returns some piece of information. A method is invoked by a method call. To call a method, you provide its name and the correct arguments that are necessary for the method to execute. Michael Eckmann - Skidmore College - CS 106 - Summer 2015

methods Here s a good analogy of a worker and boss to describe methods and their callers. A boss (the caller) asks a worker (the method that is called) to perform a task (the code in the method) and report (return results) back when the task is done. Michael Eckmann - Skidmore College - CS 106 - Summer 2015

methods All methods are defined within some class. we have seen the main method defined in the class of every application so far. Michael Eckmann - Skidmore College - CS 106 - Summer 2015

other methods we ve used We have used other methods available in the Java API, methods like parseint and parsedouble and println are available to us to use in their respective classes Integer, Double and System.out The methods in the Math class are other examples. These methods were defined for us to do a specific task. We call them when we need them. e.g. in the case of Integer.parseInt --- its task is to convert a String into an int. It takes a String as an argument (parameter) and returns a value of type int. Michael Eckmann - Skidmore College - CS 106 - Summer 2015

other methods we ve used e.g. in the case of Integer.parseInt --- its task is to convert a String into an int. It takes a String as an argument (parameter) and returns a value of type int. example of a call to this method: some_int = Integer.parseInt( some_str ); In this example, some_str is the argument that is being passed in to the parseint method and some_int is the variable that will get set to the value returned by the method. Michael Eckmann - Skidmore College - CS 106 - Summer 2015

methods We can create our own methods that we can call to perform specific tasks. Let s say we re writing a program to handle employee s salaries. We might need to compute a salary after a raise. This example method would need to have access to the current salary and the raise percentage. It would then calculate the salary after the raise and return this value. Michael Eckmann - Skidmore College - CS 106 - Summer 2015

example of a programmer-defined method we might name this method salaryafterraise we need to take in two values, one for the current salary and one for the raise percentage. What primitive type might these be? we also need to return the salary that is computed. What primitive type might this returned value be? Michael Eckmann - Skidmore College - CS 106 - Summer 2015

example of a programmer-defined method so, this method could look like: public static double salaryafterraise(double currsal, double raisepct ) { double newsal; newsal = currsal * ( 1 + raisepct / 100 ); } return newsal; Michael Eckmann - Skidmore College - CS 106 - Summer 2015

example of a programmer-defined method to call this method from some other method within the same class do the following: // example variable declarations... double newsalary; double oldsalary = 35000; double raise = 4.5; // our call to the salary_after_raise method newsalary = salaryafterraise( oldsalary, raise ); Michael Eckmann - Skidmore College - CS 106 - Fall 2015

example of a programmer-defined method Let s look at a complete program that contains this method and calls it several times. Michael Eckmann - Skidmore College - CS 106 - Fall 2015

example of a programmer-defined method When certain code can be used in several places in a program, you may want to create a method containing that code. Then, wherever that code would have been, a simple method call appears. Programmer defined methods also aid in the ability to understand a program (readability) and make changes (maintainability). Michael Eckmann - Skidmore College - CS 106 - Fall 2015

when does a method end it s execution? when it hits a return; statement when it hits a return some_expression; statement or, when it hits the right curly brace of the method whichever comes first. when the method ends its execution, the program execution continues back at the method call (from where the method was called)

more about methods methods that do not return a value are of type void (like the main method.) Methods can have 0 or more parameters separated by commas. Those with 0 parameters are defined with nothing between the parentheses to call a method with no parameters, you must still use the parentheses but with nothing between them Note that the return type of a method can be different than any or all of the types of parameters that get passed in.

Things to think about when creating our own methods Determine what job/task the method is supposed to do information needs to be provided to the method (possibly a good candidate for the parameters) information it might be able to return Michael Eckmann - Skidmore College - CS 106 - Summer 2015

example method that returns nothing and has no parameters public static void printerrormsg() { System.out.println( Invalid entry. ); System.out.println( You must reenter. ); } how to call this method: note that there are no arguments passed in nor is there a variable to which to assign the returned value (because it doesn t return a value.) printerrormsg();

example method that returns nothing but has one parameter public static void printmsg(string themsg) { System.out.println( The message is: + themsg); // note: no return statement since nothing to return // The return type of this method is void. } how to call this method: printmsg( Good afternoon gentlemen. I am a HAL 9000 computer. );

example method that returns a String but has no parameters public static String randomstring() { int num = (int) (Math.random() * 3); if (num == 0) return Hello ; if (num == 1) return Goodbye ; //if (num == 2) return $#@&!* ; } how to call this method: System.out.println( the random string is: + randomstring());

reasons to create and use methods separation and modularization of ideas is helpful when writing large programs because smaller parts of a problem are easier to solve the individual methods can be tested and confirmed correct to reduce debugging woes methods lend themselves to software reuse less code repetition more readable, better designed code

scope the scope of an identifier (a variable, reference or method name) is defined as the portion of the program that can access that identifier the two scopes for identifiers are class scope and block scope class scope starts at the opening left curly brace of a class definition and ends at its corresponding right curly brace block scope refers to identifiers that are accessible from when they are declared until the next right curly brace.

scope we've seen block scope when we declare a variable inside the main method. we've seen block scope when we declare a variable in the first expression of a for loop. we've seen block scope when we declare a variable within the curly braces of a while loop. etc. What is the effect of block scope?

variables in methods variables declared in methods are said to be local variables --- they are local to that method parameters of the method are also considered local variables to that method. they are not usable, nor are they even known outside that method --- they have block scope they are created (memory is allocated for them) on entry into the method during execution they are destroyed (memory for them is marked for deallocation) on exit from the method

some method terminology the name of the method is salaryafterraise, and the body of the method is the three lines of code between the curly braces. public double salaryafterraise(double currsal, double raisepct) { } double newsal; newsal = currsal * ( 1 + raisepct / 100 ); return newsal;

example of local variables in this method, newsal is a local variable, and the parameters of the method: currsal and raisepct are also local variables. public double salaryafterraise(double currsal, double raisepct) { double newsal; newsal = currsal * ( 1 + raisepct / 100 ); return newsal; } they are only known to this method what does that mean only known to this method

return type and argument types the return type of the method is double the two parameters are of type double public double salaryafterraise(double currsal, double raisepct) { double newsal; newsal = currsal * ( 1 + raisepct / 100 ); return newsal; } note that the return statement returns the double and this is where the execution of the method ends

method calls in the call of the method, two values are passed in to the method (we call them the arguments) and the value returned by the method call is stored in newsalary double newsalary; double oldsalary = 300; double raise = 4.5; // our call to the salary_after_raise method newsalary = salaryafterraise( oldsalary, raise );

variables passed in as arguments when calling a method the values of variables (of primitive types) that are passed into a method as arguments remain unchanged after the method ends its execution even if the corresponding parameter in the method changes its value, this change is only local to the method, and the value is not passed back out of the method. we ll see this in the factorial method on the next slide.

computefactorial method public static int computefactorial(int num) { int tempfactorial=1; while (num > 0) { tempfactorial = tempfactorial * num; num--; } return tempfactorial; }

computefactorial method this method is a programmer-defined method (that is, we make up the name and the purpose of the method.) the name of the method is: computefactorial the return type of the method is: int there is one parameter to the method, which is: num (of type int) note that the value of num inside the method changes (it gets decremented in the loop) but this is only a local change the other local variable (tempfactorial) is used to compute the factorial and its value is the one that is returned to the caller.

computefactorial method note that the value of num inside the method changes (it gets decremented in the loop) but this is only a local change the variable sent in as an argument does NOT change its value Let s write a quick program to show how the variable that is passed in to the method as an argument doesn t actually get changed. We ll print the argument s value before and after the call to the method.

promotion of argument types if a method is called with arguments of types different from those specified in the parameter list of the method definition, then Java will try to convert the value to the required type. The conversion is done according to Java s promotion rules Java only allows conversions among the primitive types from smaller to larger. primitive types from smaller to larger are: byte, short, int, long, float, double

promotion of argument types some valid type conversions: a float can be passed in to a method requiring a double an int can be passed in to a method requiring a long, or a float or a double some type conversions that would cause compiler errors: a float cannot be passed in to a method requiring an int a double cannot be passed in to a method requiring a float

a method call with the wrong type public int test_value(double input_val) { if (input_val < 0) return 1; else return 1; } Example call in some other method: int length = 3; int returned_val; returned_val = test_value(length); // call is allowed: the value of length is promoted to double;

a method to find the smallest of 4 ints we ll write a method to find the smallest of four integers (not in an array) and return that value. what might we call this method? what will the parameter list be? will we return a value? if so, what type? will we need any local variables besides the parameters?

a method to find the smallest of 4 ints public int smallest_of4(int num1, int num2, int num3, int num4) { int smallest; if (num1 < num2) // compare the first two smallest = num1; else smallest = num2; if (num3 < smallest) // compare the 3rd against the smallest so far smallest = num3; if (num4 < smallest) // compare the 4th against the smallest so far smallest = num4; } return smallest;

example call of this method int int1=14, int2=-9, int3=10, int4=879; int least; least = smallest_of4(int1, int2, int3, int4); // least will contain the value -9

let's write it by passing in an array - any ideas?