Methods CSC 121 Spring 2017 Howard Rosenthal

Size: px
Start display at page:

Download "Methods CSC 121 Spring 2017 Howard Rosenthal"

Transcription

1 Methods CSC 121 Spring 2017 Howard Rosenthal

2 Lesson Goals Understand what a method is in Java Understand Java s Math Class and how to use it Learn the syntax of method construction Learn both void methods and methods that return a value Understand method overloading Write several programs using methods 2

3 Fundamental Defini.ons A method is a named sequence of instructions that are grouped together to perform a task pretty much the same as any other program segment. The main method is required for every application. Every application starts with a main method Other methods are accessed via calls from the main method or other methods. Examples of methods that you know System.out.println() println() is the static method which means you don t have to declare an object keyboard.nextint() keyboard is the name of the object instantiated from the class Scanner nextint() is a method Note that the format is object.method(parameter list) when accessing a method in another class or object For this chapter methods that we write will all be in one class, although we will invoke methods from other classes Typically, you need to import the class and create an object from that class before you can use the methods of the class. In a few cases, no import is required, as the class is included within the java.lang package that you get automatically Other basics Some methods require one or more inputs called parameters, others none Some methods generate outputs Many common methods are prepackaged and easily accessible in Java 3

4 Why Do We Use Methods We write methods to Allow for simplified and modular development Isolating the complexity of an idea, simplifies the coding challenges and nesting in the entire programming Reduce redundant code Create a modular testing environment Improve readability 4

5 A Sample Method Let s look at a simple example of a method called Math.sqrt(x) - Math is a reference to the class that contains the method it is a static class and is imported automatically as a part of the java.lang package - sqrt is the name of the static method - x is the single parameter input into the method 5

6 Using Preexis.ng Methods Java includes many methods inside the java.lang package You only need to know the name of the class and method, its return type, and the parameters of the method to use it Other methods require importing the class that the method resides in in order to use it i.e import java.util.scanner; You still need to understand the input to and output from the method One of the nicest things about creating objects is the methods you get access to When calling a method the parameters are casted upward without loss of information You can t cast downward when passing parameters So you can pass an int value if expecting a double value, but not vice-versa When these classes use static methods you don t need to create a separate object Normally you can't call a method of a class without first creating an instance of that class using new i.e. Scanner keyboard = new Scanner(System.in); By declaring a method using the static keyword, you can call it without first creating an object because it becomes a class method (i.e. a method that belongs to a class rather than an object). That is why we can use the Math class methods without creating new objects. 6

7 The Math Class Methods Method Description abs(x) Returns absolute value of x. acos(x) Returns arc cosine of x in radians. asin(x) Returns arc sine of x in radians. atan(x) Returns arc tan of x in radians. atan2(y, x) Counterclockwise angle between x axis and point (x,y). ceil(x) Returns the smallest integer greater than or equal to x as a double. (round up). cos(x) Returns cosine of x, where x is in radians. exp(x) Returns e x floor(x) Returns the largest integer less than or equal to x as a double. (round down) log(x) Returns the natural logarithm (base E) of x. max(a, b) Returns the larger of a and b. min(a, b) Returns the lesser of a and b. pow(x, y) Returns x y random() Returns a pseudorandom number greater than or equal to 0.0 and less than 1.0. Selected based on time of day round(x) Rounds x up or down to the nearest integer as a long. It rounds.5 up. sin(x) Returns the sin of x, where x is in radians. 7

8 Some of these Methods are Overloaded Java allows 2 or more methods of the same class to share the same name this is called overloading Any overloaded method name must have a different number of parameters or different parameter types to distinguish between the methods Examples public static double min(double x, double y) public static int min(int x, int y) In both of these cases you make a call using the method min, but the results are different Is their another Math method that is overloaded?? 8

9 Some Examples Using Math Methods We will execute the MathLibraryExample.java program 9

10 Wri.ng a Method A Java method consists of a header method block really another program Methods may accept arguments A method may return a value A method may be used as part of an expression Every method that returns a value has a return statement in the method block A return statement returns the value in that statement return sum; return true; return; // if there is no return value A return statement terminates the method A method may have more than one return statement If no value is being returned, you don t need the return statement you return at the end of the method Variables declared inside a method are called local variables. They are only valid while the method is being executed and only work inside the method This includes the variables declared in the method This is another example of the scope of variables 10

11 The Method Header (1) The form of a Java method header is : modifiers return_type name(parameter_list) For now we just use public static as the modifiers this allows us to access the methods in the class directly return_type is the type of data that will be returned If no value will be returned this will use the word void instead of a data type Obviously the main method has no return type (that s why it s return value is void) The return value in the return statement cannot be of a higher type than the return type (no casting downwards) The return value can be a reference variable Only one value may be returned name is the name of the method By convention each name begins with a small letter with subsequent words in the name beginning with a capital letter drawcoordinates 11

12 The Method Header (2) The form of a Java method header is : modifiers return_type name(parameter_list) parameter list is an ordered list of typed variables The parameter list is a set of individually typed parameter in a specific order When the method is called values are passed to the parameter list of arguments The type can be a primitive variable or an object reference variable Examples of parameter lists: (boolean b1) (int x, double y) () (boolean x2, char c2) 12

13 Simple Structure for Building Methods in a Class public class MyClass { public static type method1( ) { statement; statement; } public static type methodn( ) { } statement; statement; } public static void main (String[] args) { statement; } statement; We usually put the main method last Note that all the methods are inside the class 13

14 Calling Methods A method can be invoked from The main method Another method If the method invoked doesn t return a value you just put the method name into a statement System.out.println( An example without a return value ); When there is no return value the method should be doing something If the method returns a value you must have a variable set up to receive the value (assignment statement) or have the method somewhere else where the value can be used y = Math.sqrt(x); System.out.println( The square root of y is + Math.sqrt(x)); 14

15 Formal and Actual Parameters The formal parameters are the parameters found in the method header statement. They are reinitialized each time the method is called (invoked) The scope of these parameters is the method in which they are invoked Actual parameters are the parameters used when calling the method All actual parameters must evaluate to a value of the proper type before the method is called If there is an uninitialized actual parameter then you will get an error 15

16 Some Simple Methods N/2 16

17 More Examples MethodExample001 MethodExample005 MethodExample007 Above examples found in: MethodExamples001.pdf 17

18 void Methods A void method is a method that doesn t return a value The return statement is simply: return; You can use a void method to print out a graph or a figure based on the input, without returning anything. The main program has a void return value: public static void main (String[] args) Don t create an overloaded method with the name main 18

19 More on Overloading Java allows 2 or more methods of the same class to share the same name Any overloaded method name must have a different number of parameters or at least one parameter of a different type (in the same parameter position) to distinguish between the methods Simple example with different number of parameters: public static int max(int x, int y) public static int max(int x, int y, int z) Simple example with at least one parameter of a different type : public static int max(int x, int y) public static int max(int x, double y) Warning: It is not legal to overload a method by having two identical methods (same name and number of variables of the same type in the same order) with different return types: public static int mymethod(int x) and public static double mymethod(int x) cannot appear in the same class 19

20 Global Variables and Scope You can create global variables for a class They are created within the scope of the class You need to place them inside the scope of the class but not inside any method otherwise they are only valid for that method They should be declared as static within the class, and we will just declare them as public static Here is a fragment: import java.util.scanner; //Using the scanner public class PriceAdjustment { public static Scanner keyboard = new Scanner(System.in); public static int bumpme(int price, int increase, boolean updown) { 20

21 Summary of the Rules on Scope The scope of a parameter declaration is the body of the method in which the declaration appears it only exists as long as the method is executing The scope of a local-variable declaration is from the point at which the declaration appears to the end of the block The scope of a local-variable declaration that appears in the initialization section of a for statement s header is the body of the for statement and the other expressions in the header A method or field s scope is the entire body of the class. This enables a class s instance methods to use the fields and other methods of the class (note: fields are discussed next semester) Remember any block may contain variable declarations 21

22 Summary on Calling and Using Methods There are three ways to call a method Using a method s name by itself to call another method in the same class when the method is static Using a variable that contains a reference to an object, foll0wed by a dot. This is done for non-static methods int x = keyboard.nextint(); Next semester you will learn to create your own classes with non-static methods Using the class name and a dot to call a static method of a class double z = Math.sqrt(variable); 22

23 Programming Exercises Class (1) Exercise 2 Centigrade to Fahrenheit Write a method int ctof(int x) that converts a Centigrade temperature to a Fahrenheit temperature. The conversion formula is: F= (9.0/5.0)*C + 32 The returned value should be rounded to the nearest degree. Test your method by displaying a table of Centigrade temperatures from -40 to 100, in increments of 5 degrees, with the Fahrenheit equivalents. 23

24 Programming Exercises Class (2) Exercise 15 Geometric Mean A home purchased for 300,000 dollars increases in value by 10% after one year and by another 20% after a second year. Thus, a year after purchasing the house, its value is 1.10*300,000 dollars and after two years 1.20*1.10*300,000 dollars. A third year decrease of 6% drops the value to 94% of the previous value. 0.94*1.20*1.10* = dollars. Notice that the multiplier is = The average annual increase over the three-year period is the geometric mean of 1.10, 1.20 and In general, the geometric mean of n numbers is the nth root of their product. Thus, the geometric mean of 1.10, 1.20, and.94 is (1.10*1.20*.94) 1/3 = and the product * * * equals , as does the original product,.94*1.20*1.10* In other words, the home s value after three annual changes of 10%, 20%, and 6% is the same as if, each year, the home s value increased by %. Write a program that calculates the average increase or decrease on an investment held from one to six years. Your program should first prompt for the length of time of the investment (an integer between 1 and 6, inclusive) and then the percent increase or decrease for each year. A negative number indicates a decrease. The program should display the average annual increase or decrease. For example, if a home, over a six-year period, has changed in value by 10%, 20%, 6%, 8%, 12%, and 3%, then to compute the average annual increase (or decrease), you would calculate the geometric mean of 1.1, 1.2, 1.06, 0.92, 0.88, and Hints: Overload a method, geometricmean( ). Make five versions that have two, three, four, five, and six parameters of type double. Use Math.pow(x,y). 24

25 Sample SoluMons for Class Exercise 2 Geometric Mean

26 Programming Exercises Class (3) Exercise 6 Price Adjustment Write a method int bumpme(int price, int increase, boolean updown) that accepts a price in dollars and returns a new price rounded to the nearest dollar, after increasing or decreasing the price by increase percent. If updown is true then you should increase the price; otherwise decrease the price. Write an appropriate main method to test the method. 26

27 Programming Exercises Lab (1) Exercise 3 Random Numbers Write a method int randomint(int x, int y) that returns a random integer between x and y, inclusive. x and y can be positive or negative. Remember: Math.random() returns a value greater than or equal to o and less yjan 1 of type double. 27

28 Programming Exercises Lab (2) Exercise 5 Consumer Price Index The Consumer Price Index (CPI) represents the change in the prices paid by urban consumers for a representative basket of goods and services. It is a percentage value rounded to the nearest tenth, for instance 9.2 or Write a method double getcpi() that asks a user to enter a number between -20 and 20 with one number after the decimal point. If the user supplies an unacceptable number the method should display an appropriate message ( number is too high, number is too low, number has wrong precision. and prompt the user for another value. When the user succeeds the method should return the number. Test your number by continually prompting a user for a value and displaying the value. When you are confident that the method is correct write a second method double inflation(double cpi, double expenses) that accepts the CPI and last year's annual expenses. Method inflation( ) returns what you might expect to pay for the same goods in the coming year. Write a main method that calls both getcpi() and inflation( ). 28

Methods CSC 121 Fall 2016 Howard Rosenthal

Methods CSC 121 Fall 2016 Howard Rosenthal Methods CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand what a method is in Java Understand Java s Math Class and how to use it Learn the syntax of method construction Learn both void methods

More information

Methods CSC 121 Fall 2014 Howard Rosenthal

Methods CSC 121 Fall 2014 Howard Rosenthal Methods CSC 121 Fall 2014 Howard Rosenthal Lesson Goals Understand what a method is in Java Understand Java s Math Class Learn the syntax of method construction Learn both void methods and methods that

More information

CT 229 Java Syntax Continued

CT 229 Java Syntax Continued CT 229 Java Syntax Continued 06/10/2006 CT229 Lab Assignments Due Date for current lab assignment : Oct 8 th Before submission make sure that the name of each.java file matches the name given in the assignment

More information

C++ Programming Lecture 11 Functions Part I

C++ Programming Lecture 11 Functions Part I C++ Programming Lecture 11 Functions Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department Introduction Till now we have learned the basic concepts of C++. All the programs

More information

www.thestudycampus.com Methods Let s imagine an automobile factory. When an automobile is manufactured, it is not made from basic raw materials; it is put together from previously manufactured parts. Some

More information

The Math Class (Outsource: Math Class Supplement) Random Numbers. Lab 06 Math Class

The Math Class (Outsource: Math Class Supplement) Random Numbers. Lab 06 Math Class The (Outsource: Supplement) The includes a number of constants and methods you can use to perform common mathematical functions. A commonly used constant found in the Math class is Math.PI which is defined

More information

What did we talk about last time? Examples switch statements

What did we talk about last time? Examples switch statements Week 4 - Friday What did we talk about last time? Examples switch statements History of computers Hardware Software development Basic Java syntax Output with System.out.print() Mechanical Calculation

More information

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

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program

More information

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

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program

More information

static int min(int a, int b) Returns the smaller of two int values. static double pow(double a,

static int min(int a, int b) Returns the smaller of two int values. static double pow(double a, The (Outsource: Supplement) The includes a number of constants and methods you can use to perform common mathematical functions. A commonly used constant found in the Math class is Math.PI which is defined

More information

The Number object. to set specific number types (like integer, short, In JavaScript all numbers are 64bit floating point

The Number object. to set specific number types (like integer, short, In JavaScript all numbers are 64bit floating point Internet t Software Technologies JavaScript part three IMCNE A.A. 2008/09 Gabriele Cecchetti The Number object The JavaScript Number object does not allow you to set specific number types (like integer,

More information

1001ICT Introduction To Programming Lecture Notes

1001ICT Introduction To Programming Lecture Notes 1001ICT Introduction To Programming Lecture Notes School of Information and Communication Technology Griffith University Semester 1, 2015 1 M Environment console M.1 Purpose This environment supports programming

More information

Introduction to Computer Programming in Python Dr. William C. Bulko. Data Types

Introduction to Computer Programming in Python Dr. William C. Bulko. Data Types Introduction to Computer Programming in Python Dr William C Bulko Data Types 2017 What is a data type? A data type is the kind of value represented by a constant or stored by a variable So far, you have

More information

4. Java Project Design, Input Methods

4. Java Project Design, Input Methods 4-1 4. Java Project Design, Input Methods Review and Preview You should now be fairly comfortable with creating, compiling and running simple Java projects. In this class, we continue learning new Java

More information

Product Price Formula extension for Magento2. User Guide

Product Price Formula extension for Magento2. User Guide Product Price Formula extension for Magento2 User Guide version 1.0 Page 1 Contents 1. Introduction... 3 2. Installation... 3 2.1. System Requirements... 3 2.2. Installation...... 3 2.3. License... 3 3.

More information

Lecture 5: Methods CS2301

Lecture 5: Methods CS2301 Lecture 5: Methods NADA ALZAHRANI CS2301 1 Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. 2 Solution public static int sum(int i1, int i2) { int

More information

Repetition CSC 121 Fall 2014 Howard Rosenthal

Repetition CSC 121 Fall 2014 Howard Rosenthal Repetition CSC 121 Fall 2014 Howard Rosenthal Lesson Goals Learn the following three repetition methods, their similarities and differences, and how to avoid common errors when using them: while do-while

More information

Goals for This Lecture:

Goals for This Lecture: Goals for This Lecture: Understand integer arithmetic Understand mixed-mode arithmetic Understand the hierarchy of arithmetic operations Introduce the use of intrinsic functions Real Arithmetic Valid expressions

More information

CEN 414 Java Programming

CEN 414 Java Programming CEN 414 Java Programming Instructor: H. Esin ÜNAL SPRING 2017 Slides are modified from original slides of Y. Daniel Liang WEEK 2 ELEMENTARY PROGRAMMING 2 Computing the Area of a Circle public class ComputeArea

More information

MYSQL NUMERIC FUNCTIONS

MYSQL NUMERIC FUNCTIONS MYSQL NUMERIC FUNCTIONS http://www.tutorialspoint.com/mysql/mysql-numeric-functions.htm Copyright tutorialspoint.com MySQL numeric functions are used primarily for numeric manipulation and/or mathematical

More information

C++ Overview. Chapter 1. Chapter 2

C++ Overview. Chapter 1. Chapter 2 C++ Overview Chapter 1 Note: All commands you type (including the Myro commands listed elsewhere) are essentially C++ commands. Later, in this section we will list those commands that are a part of the

More information

CP122 Computer Science I. Chapter 3: Methods/Functions

CP122 Computer Science I. Chapter 3: Methods/Functions CP122 Computer Science I Chapter 3: Methods/Functions Offline viewing of some Netflix shows now available Tech News Tech News Offline viewing of some Netflix shows now available Consumer Review Fairness

More information

Custom Variables (Virtual Variables)

Custom Variables (Virtual Variables) Page 1 of 7 Custom Variables (Virtual Variables) Allocate not only allows you to select standard variables, but also allows you to create your own unique demographic variables. You may create new variables

More information

Methods (Deitel chapter 6)

Methods (Deitel chapter 6) Methods (Deitel chapter 6) 1 Plan 2 Introduction Program Modules in Java Math-Class Methods Method Declarations Argument Promotion Java API Packages Random-Number Generation Scope of Declarations Methods

More information

Methods (Deitel chapter 6)

Methods (Deitel chapter 6) 1 Plan 2 Methods (Deitel chapter ) Introduction Program Modules in Java Math-Class Methods Method Declarations Argument Promotion Java API Packages Random-Number Generation Scope of Declarations Methods

More information

Key Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent

Key Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent Programming 2 Key Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent information Input can receive information

More information

Programming Exercise 7: Static Methods

Programming Exercise 7: Static Methods Programming Exercise 7: Static Methods Due date for section 001: Monday, February 29 by 10 am Due date for section 002: Wednesday, March 2 by 10 am Purpose: Introduction to writing methods and code re-use.

More information

CSI31 Lecture 5. Topics: 3.1 Numeric Data Types 3.2 Using the Math Library 3.3 Accumulating Results: Factorial

CSI31 Lecture 5. Topics: 3.1 Numeric Data Types 3.2 Using the Math Library 3.3 Accumulating Results: Factorial CSI31 Lecture 5 Topics: 3.1 Numeric Data Types 3.2 Using the Math Library 3.3 Accumulating Results: Factorial 1 3.1 Numberic Data Types When computers were first developed, they were seen primarily as

More information

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4 BIL 104E Introduction to Scientific and Engineering Computing Lecture 4 Introduction Divide and Conquer Construct a program from smaller pieces or components These smaller pieces are called modules Functions

More information

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements COMP-202 Unit 4: Programming With Iterations CONTENTS: The while and for statements Introduction (1) Suppose we want to write a program to be used in cash registers in stores to compute the amount of money

More information

CSC Algorithms and Data Structures I. Midterm Examination February 25, Name:

CSC Algorithms and Data Structures I. Midterm Examination February 25, Name: CSC 1051-001 Algorithms and Data Structures I Midterm Examination February 25, 2016 Name: Question Value Score 1 10 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 10 10 TOTAL 100 Please answer questions in the

More information

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Repe$$on CSC 121 Fall 2015 Howard Rosenthal Repe$$on CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Learn the following three repetition methods, their similarities and differences, and how to avoid common errors when using them: while do-while

More information

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

To define methods, invoke methods, and pass arguments to a method ( ). To develop reusable code that is modular, easy-toread, easy-to-debug, 1 To define methods, invoke methods, and pass arguments to a method ( 5.2-5.5). To develop reusable code that is modular, easy-toread, easy-to-debug, and easy-to-maintain. ( 5.6). To use method overloading

More information

Fundamentals of Programming Data Types & Methods

Fundamentals of Programming Data Types & Methods Fundamentals of Programming Data Types & Methods By Budditha Hettige Overview Summary (Previous Lesson) Java Data types Default values Variables Input data from keyboard Display results Methods Operators

More information

AP CS Unit 3: Control Structures Notes

AP CS Unit 3: Control Structures Notes AP CS Unit 3: Control Structures Notes The if and if-else Statements. These statements are called control statements because they control whether a particular block of code is executed or not. Some texts

More information

Arrays and Lists CSC 121 Fall 2014 Howard Rosenthal

Arrays and Lists CSC 121 Fall 2014 Howard Rosenthal Arrays and Lists CSC 121 Fall 2014 Howard Rosenthal Lesson Goals Understand what an array is Understand how to declare arrays Understand what reference variables are Understand how to pass arrays to methods

More information

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

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled Interpreted vs Compiled Python 1 Java Interpreted Easy to run and test Quicker prototyping Program runs slower Compiled Execution time faster Virtual Machine compiled code portable Java Compile > javac

More information

Methods: A Deeper Look

Methods: A Deeper Look 1 2 7 Methods: A Deeper Look OBJECTIVES In this chapter you will learn: How static methods and variables are associated with an entire class rather than specific instances of the class. How to use random-number

More information

Chapter 2. Outline. Simple C++ Programs

Chapter 2. Outline. Simple C++ Programs Chapter 2 Simple C++ Programs Outline Objectives 1. Building C++ Solutions with IDEs: Dev-cpp, Xcode 2. C++ Program Structure 3. Constant and Variables 4. C++ Operators 5. Standard Input and Output 6.

More information

Introduction to Computer Science and Object-Oriented Programming

Introduction to Computer Science and Object-Oriented Programming COMP 111 Introduction to Computer Science and Object-Oriented Programming Values Judgment Programs Manipulate Values Inputs them Stores them Calculates new values from existing ones Outputs them In Java

More information

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University Lesson #3 Variables, Operators, and Expressions Variables We already know the three main types of variables in C: int, char, and double. There is also the float type which is similar to double with only

More information

St. Edmund Preparatory High School Brooklyn, NY

St. Edmund Preparatory High School Brooklyn, NY AP Computer Science Mr. A. Pinnavaia Summer Assignment St. Edmund Preparatory High School Name: I know it has been about 7 months since you last thought about programming. It s ok. I wouldn t want to think

More information

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Repe$$on CSC 121 Spring 2017 Howard Rosenthal Repe$$on CSC 121 Spring 2017 Howard Rosenthal Lesson Goals Learn the following three repetition structures in Java, their syntax, their similarities and differences, and how to avoid common errors when

More information

Numerical Data. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Numerical Data. CS 180 Sunil Prabhakar Department of Computer Science Purdue University Numerical Data CS 180 Sunil Prabhakar Department of Computer Science Purdue University Problem Write a program to compute the area and perimeter of a circle given its radius. Requires that we perform operations

More information

APCS Semester #1 Final Exam Practice Problems

APCS Semester #1 Final Exam Practice Problems Name: Date: Per: AP Computer Science, Mr. Ferraro APCS Semester #1 Final Exam Practice Problems The problems here are to get you thinking about topics we ve visited thus far in preparation for the semester

More information

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

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02 Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02 Hello, in this lecture we will learn about some fundamentals concepts of java.

More information

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

Chapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. Chapter 5 Methods 1 Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. 2 Problem int sum = 0; for (int i = 1; i

More information

C Functions. 5.2 Program Modules in C

C Functions. 5.2 Program Modules in C 1 5 C Functions 5.2 Program Modules in C 2 Functions Modules in C Programs combine user-defined functions with library functions - C standard library has a wide variety of functions Function calls Invoking

More information

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

COP3502 Programming Fundamentals for CIS Majors 1. Instructor: Parisa Rashidi COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi Chapter 4 Loops for while do-while Last Week Chapter 5 Methods Input arguments Output Overloading Code reusability Scope of

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

Computer Science & Engineering 150A Problem Solving Using Computers

Computer Science & Engineering 150A Problem Solving Using Computers Computer Science & Engineering 150A Problem Solving Using Computers Lecture 03 - Stephen Scott (Adapted from Christopher M. Bourke) 1 / 41 Fall 2009 Chapter 3 3.1 Building Programs from Existing Information

More information

CS111: PROGRAMMING LANGUAGE II

CS111: PROGRAMMING LANGUAGE II 1 CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 1: Introduction Lecture Contents 2 Course info Why programming?? Why Java?? Write once, run anywhere!! Java basics Input/output Variables

More information

CSC 1051 Algorithms and Data Structures I. Midterm Examination February 25, Name: KEY A

CSC 1051 Algorithms and Data Structures I. Midterm Examination February 25, Name: KEY A CSC 1051 Algorithms and Data Structures I Midterm Examination February 25, 2016 Name: KEY A Question Value Score 1 10 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 10 10 TOTAL 100 Please answer questions in

More information

Java Classes: Math, Integer A C S L E C T U R E 8

Java Classes: Math, Integer A C S L E C T U R E 8 Java Classes: Math, Integer A C S - 1903 L E C T U R E 8 Math class Math class is a utility class You cannot create an instance of Math All references to constants and methods will use the prefix Math.

More information

Introduction to Computer Science Unit 2. Notes

Introduction to Computer Science Unit 2. Notes Introduction to Computer Science Unit 2. Notes Name: Objectives: By the completion of this packet, students should be able to describe the difference between.java and.class files and the JVM. create and

More information

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 3. Existing Information. Notes. Notes. Notes. Lecture 03 - Functions

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 3. Existing Information. Notes. Notes. Notes. Lecture 03 - Functions Computer Science & Engineering 150A Problem Solving Using Computers Lecture 03 - Functions Stephen Scott (Adapted from Christopher M. Bourke) Fall 2009 1 / 1 cbourke@cse.unl.edu Chapter 3 3.1 Building

More information

Introduction to Computer Science Unit 2. Notes

Introduction to Computer Science Unit 2. Notes Introduction to Computer Science Unit 2. Notes Name: Objectives: By the completion of this packet, students should be able to describe the difference between.java and.class files and the JVM. create and

More information

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

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation. Lab 4 Functions Introduction: A function : is a collection of statements that are grouped together to perform an operation. The following is its format: type name ( parameter1, parameter2,...) { statements

More information

Python Programming: An Introduction to Computer Science

Python Programming: An Introduction to Computer Science Python Programming: An Introduction to Computer Science Chapter 3 Computing with Numbers Python Programming, 3/e 1 Objectives n To understand the concept of data types. n To be familiar with the basic

More information

Primitive Data Types: Intro

Primitive Data Types: Intro Primitive Data Types: Intro Primitive data types represent single values and are built into a language Java primitive numeric data types: 1. Integral types (a) byte (b) int (c) short (d) long 2. Real types

More information

Chapter 3. Computer Science & Engineering 155E Computer Science I: Systems Engineering Focus. Existing Information.

Chapter 3. Computer Science & Engineering 155E Computer Science I: Systems Engineering Focus. Existing Information. Chapter 3 Computer Science & Engineering 155E Computer Science I: Systems Engineering Focus Lecture 03 - Introduction To Functions Christopher M. Bourke cbourke@cse.unl.edu 3.1 Building Programs from Existing

More information

PRIMITIVE VARIABLES. CS302 Introduction to Programming University of Wisconsin Madison Lecture 3. By Matthew Bernstein

PRIMITIVE VARIABLES. CS302 Introduction to Programming University of Wisconsin Madison Lecture 3. By Matthew Bernstein PRIMITIVE VARIABLES CS302 Introduction to Programming University of Wisconsin Madison Lecture 3 By Matthew Bernstein matthewb@cs.wisc.edu Variables A variable is a storage location in your computer Each

More information

CS110: PROGRAMMING LANGUAGE I

CS110: PROGRAMMING LANGUAGE I CS110: PROGRAMMING LANGUAGE I Computer Science Department Lecture 8: Methods Lecture Contents: 2 Introduction Program modules in java Defining Methods Calling Methods Scope of local variables Passing Parameters

More information

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

Java Methods. Lecture 8 COP 3252 Summer May 23, 2017 Java Methods Lecture 8 COP 3252 Summer 2017 May 23, 2017 Java Methods In Java, the word method refers to the same kind of thing that the word function is used for in other languages. Specifically, a method

More information

Lab5. Wooseok Kim

Lab5. Wooseok Kim Lab5 Wooseok Kim wkim3@albany.edu www.cs.albany.edu/~wooseok/201 Question Answer Points 1 A or B 8 2 A 8 3 D 8 4 20 5 for class 10 for main 5 points for output 5 D or E 8 6 B 8 7 1 15 8 D 8 9 C 8 10 B

More information

Downloaded from Chapter 2. Functions

Downloaded from   Chapter 2. Functions Chapter 2 Functions After studying this lesson, students will be able to: Understand and apply the concept of module programming Write functions Identify and invoke appropriate predefined functions Create

More information

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

Chapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. Chapter 5 Methods rights reserved. 0132130807 1 Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. rights reserved. 0132130807 2 1 Problem int sum =

More information

CS111: PROGRAMMING LANGUAGE II

CS111: PROGRAMMING LANGUAGE II CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 1(c): Java Basics (II) Lecture Contents Java basics (part II) Conditions Loops Methods Conditions & Branching Conditional Statements A

More information

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types and

More information

Computer Science is...

Computer Science is... Computer Science is... Bioinformatics Computer scientists develop algorithms and statistical techniques to interpret huge amounts of biological data. Example: mapping the human genome. Right: 3D model

More information

Introduction to Programming

Introduction to Programming Introduction to Programming Department of Computer Science and Information Systems Tingting Han (afternoon), Steve Maybank (evening) tingting@dcs.bbk.ac.uk sjmaybank@dcs.bbk.ac.uk Autumn 2017 Week 4: More

More information

Introduction to Java Applications

Introduction to Java Applications 2 Introduction to Java Applications OBJECTIVES In this chapter you will learn: To write simple Java applications. To use input and output statements. Java s primitive types. Basic memory concepts. To use

More information

LAB 13: ARRAYS (ONE DIMINSION)

LAB 13: ARRAYS (ONE DIMINSION) Statement Purpose: The purpose of this Lab. is to practically familiarize student with the concept of array and related operations performed on array. Activity Outcomes: As a second Lab on Chapter 7, this

More information

Introduction to Python, Cplex and Gurobi

Introduction to Python, Cplex and Gurobi Introduction to Python, Cplex and Gurobi Introduction Python is a widely used, high level programming language designed by Guido van Rossum and released on 1991. Two stable releases: Python 2.7 Python

More information

Object-Oriented Programming

Object-Oriented Programming Object-Oriented Programming Java Syntax Program Structure Variables and basic data types. Industry standard naming conventions. Java syntax and coding conventions If Then Else Case statements Looping (for,

More information

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2009) - All Sections Midterm Examination

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2009) - All Sections Midterm Examination First Name: Last Name: McGill ID: Section: Faculty of Science COMP-202A - Introduction to Computing I (Fall 2009) - All Sections Midterm Examination Tuesday, November 3, 2009 Examiners: Mathieu Petitpas

More information

6-1 (Function). (Function) !*+!"#!, Function Description Example. natural logarithm of x (base e) rounds x to smallest integer not less than x

6-1 (Function). (Function) !*+!#!, Function Description Example. natural logarithm of x (base e) rounds x to smallest integer not less than x (Function) -1.1 Math Library Function!"#! $%&!'(#) preprocessor directive #include !*+!"#!, Function Description Example sqrt(x) square root of x sqrt(900.0) is 30.0 sqrt(9.0) is 3.0 exp(x) log(x)

More information

Engineering Problem Solving with C++, Etter/Ingber

Engineering Problem Solving with C++, Etter/Ingber Engineering Problem Solving with C++, Etter/Ingber Chapter 2 Simple C++ Programs C++, Second Edition, J. Ingber 1 Simple C++ Programs Program Structure Constants and Variables C++ Operators Standard Input

More information

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

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Dr. Marenglen Biba (C) 2010 Pearson Education, Inc. All rights reserved. Java application A computer program that executes when you use the java command to launch the Java Virtual Machine

More information

Ordinary Differential Equation Solver Language (ODESL) Reference Manual

Ordinary Differential Equation Solver Language (ODESL) Reference Manual Ordinary Differential Equation Solver Language (ODESL) Reference Manual Rui Chen 11/03/2010 1. Introduction ODESL is a computer language specifically designed to solve ordinary differential equations (ODE

More information

2/9/2012. Chapter Four: Fundamental Data Types. Chapter Goals

2/9/2012. Chapter Four: Fundamental Data Types. Chapter Goals Chapter Four: Fundamental Data Types Chapter Goals To understand integer and floating-point numbers To recognize the limitations of the numeric types To become aware of causes for overflow and roundoff

More information

Arrays and Lists CSC 121 Fall 2016 Howard Rosenthal

Arrays and Lists CSC 121 Fall 2016 Howard Rosenthal Arrays and Lists CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand what an array is Understand how to declare arrays Understand what reference variables are Understand how to pass arrays to methods

More information

Introduction to PartSim and Matlab

Introduction to PartSim and Matlab NDSU Introduction to PartSim and Matlab pg 1 PartSim: www.partsim.com Introduction to PartSim and Matlab PartSim is a free on-line circuit simulator that we use in Circuits and Electronics. It works fairly

More information

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

Chapter 5 Methods. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. Chapter 5 Methods 1 Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. 2 Problem int sum = 0; for (int i = 1; i

More information

XQ: An XML Query Language Language Reference Manual

XQ: An XML Query Language Language Reference Manual XQ: An XML Query Language Language Reference Manual Kin Ng kn2006@columbia.edu 1. Introduction XQ is a query language for XML documents. This language enables programmers to express queries in a few simple

More information

Computer Programming, I. Laboratory Manual. Experiment #7. Methods

Computer Programming, I. Laboratory Manual. Experiment #7. Methods Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Experiment #7

More information

Lab5. Wooseok Kim

Lab5. Wooseok Kim Lab5 Wooseok Kim wkim3@albany.edu www.cs.albany.edu/~wooseok/201 Question Answer Points 1 A 8 2 A 8 3 E 8 4 D 8 5 20 5 for class 10 for main 5 points for output 6 A 8 7 B 8 8 0 15 9 D 8 10 B 8 Question

More information

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

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions Faculty of Engineering Computer Engineering Department Islamic University of Gaza 2013 C++ Programming Language Lab # 6 Functions C++ Programming Language Lab # 6 Functions Objective: To be familiar with

More information

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

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG 1 Notice Assignments Reading Assignment: Chapter 3: Introduction to Parameters and Objects The Class 10 Exercise

More information

Chapter 5 Methods / Functions

Chapter 5 Methods / Functions Chapter 5 Methods / Functions 1 Motivations A method is a construct for grouping statements together to perform a function. Using a method, you can write the code once for performing the function in a

More information

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types

More information

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Experiment #2

More information

CIS133J. Working with Numbers in Java

CIS133J. Working with Numbers in Java CIS133J Working with Numbers in Java Contents: Using variables with integral numbers Using variables with floating point numbers How to declare integral variables How to declare floating point variables

More information

Section 2.2 Your First Program in Java: Printing a Line of Text

Section 2.2 Your First Program in Java: Printing a Line of Text Chapter 2 Introduction to Java Applications Section 2.2 Your First Program in Java: Printing a Line of Text 2.2 Q1: End-of-line comments that should be ignored by the compiler are denoted using a. Two

More information

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

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods Islamic University of Gaza Faculty of Engineering Computer Engineering Dept. Computer Programming Lab (ECOM 2114) ABSTRACT In this Lab you will learn to define and invoke void and return java methods JAVA

More information

1 class Lecture5 { 2 3 "Methods" / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 0 / Zheng-Liang Lu Java Programming 176 / 199

1 class Lecture5 { 2 3 Methods / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 0 / Zheng-Liang Lu Java Programming 176 / 199 1 class Lecture5 { 2 3 "Methods" 4 5 } 6 7 / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 0 / Zheng-Liang Lu Java Programming 176 / 199 Methods 2 Methods can be used to define reusable code, and organize

More information

Mr. Monroe s Guide to Mastering Java Syntax

Mr. Monroe s Guide to Mastering Java Syntax Mr. Monroe s Guide to Mastering Java Syntax Getting Started with Java 1. Download and install the official JDK (Java Development Kit). 2. Download an IDE (Integrated Development Environment), like BlueJ.

More information

Arrays and Lists CSC 121 Fall 2015 Howard Rosenthal

Arrays and Lists CSC 121 Fall 2015 Howard Rosenthal Arrays and Lists CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Understand what an array is Understand how to declare arrays Understand what reference variables are Understand how to pass arrays to methods

More information

Programming with Java

Programming with Java Programming with Java Data Types & Input Statement Lecture 04 First stage Software Engineering Dep. Saman M. Omer 2017-2018 Objectives q By the end of this lecture you should be able to : ü Know rules

More information

Introduction to Engineering gii

Introduction to Engineering gii 25.108 Introduction to Engineering gii Dr. Jay Weitzen Lecture Notes I: Introduction to Matlab from Gilat Book MATLAB - Lecture # 1 Starting with MATLAB / Chapter 1 Topics Covered: 1. Introduction. 2.

More information