Fundamentals of Programming. Laboratory 5 Methods. General-purpose and user - defined methods



Similar documents
Chapter 5 Functions. Introducing Functions

C Programming Language

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

Scanner sc = new Scanner(System.in); // scanner for the keyboard. Scanner sc = new Scanner(System.in); // scanner for the keyboard

Chapter 3. Input and output. 3.1 The System class

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

AP Computer Science Static Methods, Strings, User Input

Building Java Programs

Introduction to Java

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

Building Java Programs

Basics of Java Programming Input and the Scanner class

How do you compare numbers? On a number line, larger numbers are to the right and smaller numbers are to the left.

Part I. Multiple Choice Questions (2 points each):

Topic 11 Scanner object, conditional execution

Chapter 2: Elements of Java

AP Computer Science Java Subset

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Interactive Applications (CLI) and Math

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Building Java Programs

Sample CSE8A midterm Multiple Choice (circle one)

ALGORITHMS AND FLOWCHARTS

CSCI 1301: Introduction to Computing and Programming Summer 2015 Project 1: Credit Card Pay Off

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Example of a Java program

Introduction to Java. CS 3: Computer Programming in Java

Programmierpraktikum

Week 1: Review of Java Programming Basics

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Comp 248 Introduction to Programming

Final Exam Review: VBA

Install Java Development Kit (JDK) 1.8

More on Objects and Classes

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

Chapter 2 Elementary Programming

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

Arrays in Java. Working with Arrays

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

The OptQuest Engine Java and.net Developer's Guilde

Introduction to Programming

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

Breaking The Code. Ryan Lowe. Ryan Lowe is currently a Ball State senior with a double major in Computer Science and Mathematics and

Data Structures Lecture 1

1.1 Your First Program

CS1020 Data Structures and Algorithms I Lecture Note #1. Introduction to Java

Advanced GMAT Math Questions

Lecture 13 - Basic Number Theory.

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Moving from CS 61A Scheme to CS 61B Java

J a v a Quiz (Unit 3, Test 0 Practice)

AP Computer Science Java Mr. Clausen Program 9A, 9B

Object-Oriented Programming in Java

For live Java EE training, please see training courses

Sources: On the Web: Slides will be available on:

Computer Programming I

Building Java Programs

Programming in Java Course Technology, a part of Cengage Learning.

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

6.1. Example: A Tip Calculator 6-1

ALGORITHMS AND FLOWCHARTS. By Miss Reham Tufail

(Eng. Hayam Reda Seireg) Sheet Java

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

CS 106 Introduction to Computer Science I

Iteration CHAPTER 6. Topic Summary

Chapter 2. println Versus print. Formatting Output withprintf. System.out.println for console output. console output. Console Input and Output

Variables, Constants, and Data Types

8 Primes and Modular Arithmetic

3 length + 23 size = 2

Arrays. Introduction. Chapter 7

Chapter 2 Introduction to Java programming

Java Crash Course Part I

History OOP languages Year Language 1967 Simula Smalltalk

= = 3 4, Now assume that P (k) is true for some fixed k 2. This means that

Homework/Program #5 Solutions

You are to simulate the process by making a record of the balls chosen, in the sequence in which they are chosen. Typical output for a run would be:

PROG0101 Fundamentals of Programming PROG0101 FUNDAMENTALS OF PROGRAMMING. Chapter 3 Algorithms

Section IV.1: Recursive Algorithms and Recursion Trees

AP Computer Science File Input with Scanner

Java Basics: Data Types, Variables, and Loops

LOOPS CHAPTER CHAPTER GOALS

The C Programming Language course syllabus associate level

Java Programming Fundamentals

Pseudo code Tutorial and Exercises Teacher s Version

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Informatica e Sistemi in Tempo Reale

CS170 Lab 11 Abstract Data Types & Objects

Grade 7/8 Math Circles Fall 2012 Factors and Primes

Third AP Edition. Object-Oriented Programming and Data Structures. Maria Litvin. Gary Litvin. Phillips Academy, Andover, Massachusetts

Homework until Test #2

1.4 Arrays Introduction to Programming in Java: An Interdisciplinary Approach Robert Sedgewick and Kevin Wayne Copyright /6/11 12:33 PM!

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Object Oriented Software Design

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

Java Interview Questions and Answers

1. Define: (a) Variable, (b) Constant, (c) Type, (d) Enumerated Type, (e) Identifier.

Transcription:

Fundamentals of Programming Laboratory 5 Methods. General-purpose and user - defined methods

What is a method? Block of code that receives its own identifier - i.e. can be executed using its name Different names in programming languages: method, function, procedure A method receives data through parameters, and/or operates on globally accessible variables

Procedural Programming vs Object Oriented Programming In PP data is kept separate from functionality procedures/functions operate on data passed to them, and have only temporary variables In OOP a method needs to belong to a class or an object, and has access to object s data Java is a strictly OOP language, thus all methods need to be put in classes However, for now we will try to avoid dealing with objects and work on general-purpose methods The goal is to get you used to the idea of dividing your program into procedures/functions

CALLING METHODS Methods are executed using their assigned identifiers, parentheses and if needed parameters. If the method belongs to a class or object, the name of that class or object preceeds the method and is followed by a dot (multiple dots in case of subclasses). For example: System.out.print( Text passed as parameter ); Calls the method print() that belongs to the class System and subclass out, passing the text as the argument (a.k.a. parameter).

EXAMPLE MATHEMATICAL METHOD abs() Consider the mathematical method named abs( ), which calculates the absolute value of a number. a = Math.abs(number); class method argument The items that are passed to the method through the parentheses, as we have noted previously in relation to the println( ) method, are called arguments of the method and constitute its input data.

METHOD OVERLOADING A method is definded to work with a fixed set of parameters. However, different versions of the same method can be prepared for different parameter data types, or a different number of parameters. This is called method overloading. Expression Value Returned Returned Data Type Math.abs (-4) 4 integer Math.abs (-17.25f) 17.25 floating-point Math.abs(-23456.78) 23456.78 double-precision

MATHEMATICAL METHODS The arguments that are passed to a method need not be single constants. An expression, a variable or another method can also be an argument. For example, the following arguments are valid for the given methods: a = Math.sqrt(4.0 + 5.3 * 4.0); b = 4 * Math.sqrt(4.5 * 10.0) - 2.0; c = Math.sqrt(Math.pow(Math.abs(numl),num2));

Common Java Math Methods Method Name Description Returned Value abs(x) absolute value same data type as argument pow(xl,x2) xl raised to the x2 power double sqrt(x) square root of x double log(x) natural logarithm of x double exp(x) e raised to the x power double ceil(x) floor(x) smallest integer value that is not less than x largest integer value that is not greater than x double double min(x,y) smaller of its two arguments same data type as arguments max(x,y) larger of its two arguments same data type as arguments round(x) rounded value integer random() random number between double 0.0 incl. and 1.0 excl. sin(x) sine of x (x in radians) double

QUESTIONS Write valid Java statements to determine: a. The square root of 6.37 b. The absolute value of a 2 - b 2 c. The value of e raised to the 3rd power ORAL EXERCISE

EXERCISE 1 Write a program that determines the time it takes a ball to hit the ground after it has been dropped from an 800-foot tower. The mathematical formula to calculate the time, in seconds, that it takes to fall a given distance, in feet, is: time = sqrt(2 * distance / g) where g is the gravitational constant equal to 32.2 ft/sec^2. PROGRAMMING EXERCISE

EXERCISE 2 A model of worldwide population, in billions of people, after the year 2000 is given by the equation Population = 6.0 e 0.02 [Year 2000 ] Using this formula, write, compile, and execute a Java program to estimate the worldwide population in years 2012-2020. PROGRAMMING EXERCISE

EXERCISE 3 Create a series of 10 random numbers using Java's library method Math.random( ) The numbers can be equal to 1,2,3,4,5 or 6 Hint: Use the Math.ceil() method, Math.round() and/or cast value to int casting: int x = (int)(2.7*3.5); PROGRAMMING EXERCISE

DECLARING METHODS To create your own method, you need to write its header and body inside a class but outside any other methods (such as your main method). The header contains: keywords for scope, return type, method name, arguments Copy the example on the next two slides to your computers to work on.

CALLING AND PASSING DATA TO A METHOD import java.util.*; public class Main { public static void main(string[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter the value of firstnum: "); double firstnum = input.nextdouble(); System.out.print("Enter the value of secnum: "); double secnum = input.nextdouble(); printmaximum(firstnum, secnum); // the method is called here } // end of main() method // following is the findmaximum() method

CALLING AND PASSING DATA TO A METHOD HEADER public static void printmaximum(double x, double y) { // start of method body double max; // variable declaration if (x >= y) // find the maximum number max = x; else max = y; System.out.print("The maximum of "+x+" and "+y+" is "+max); } // end of method body and end of method } // end of class

DECLARING THE METHOD HEADER public static void printmaximum(double x, double y) { //body of the method }

THE HEADER OF THE METHOD public static void printmaximum(double x, double y) KEYWORDS (for now all our methods will be general purpose, so public static) RETURN DATA TYPE METHOD IDENTIFIER ARGUMENTS AND THEIR DATA TYPES Note: If the method is given a return data type, then in the body it must contain a statement: return(expression); Where expression is a value of that data type.

CALLING THE METHOD printmaximum (firstnum, secnum); This statemement calls findmaximum( ) The value in firstnum is passed The value in secnum is passed printmaximum() The parameter named x The parameter named y

QUESTIONS For the following method headers, determine the number, type, and order (sequence) of the values that must be passed to the method: public static void price (int type, double yield, double maturity) public static void interest (char flag, double price, double time) ORAL EXERCISE

QUESTIONS Write a general-purpose method named findabs ( ) that accepts a double-precision number passed to it, computes its absolute value, and displays the absolute value. ORAL EXERCISE

EXERCISE: Write method headers for the following: a. A general-purpose method named check (), which has three parameters. The first parameter should accept an integer number, the second parameter a floating-point number, and the third parameter a double-precision number. The method returns no value. b. A general-purpose method named mult ( ) that accepts two floating-point numbers as parameters, multiplies these two numbers, and returns the result. BOARD EXERCISE

EXERCISE 4 According to Plato, a man should marry a woman whose age is half his age plus seven years. Write a program that requests a man s age as input and gives the ideal age of his wife. Use two separate methods for input and output. Your main method should look like this: public static void main(string[] args) { int age; age = askuser(); calculateandprintwifeage(age); } PROGRAMMING EXERCISE

EXERCISE 5 To determine the number of square centimeters of tin needed to make a tin can, add the square of the radius of the can to the product of the radius and height of the can, and then multiply this sum by 6.283. Write a program that requests the radius and height of a tin can in centimeters as input and displays the number of square centimeters required to make the can. In the program create a method that asks a user for a value and returns a double, and can be called like this: double a = askuser( Please give the radius ); PROGRAMMING EXERCISE

HOMEWORK 1 Prepare a program to check whether a number is a prime number. Inside your Main class create a method checkprime() that accepts an integer argument and returns a boolean true if the argument was prime. if(checkprime(x)) { } Repeat checking for any number entered by the user, until he enters 0. For checking, best use the modulo operator % to find the remainder from division. Bonus: Have checkprime() return the number of modulo operations that were performed and look for ways to improve the algorithm to perform as few operations as possible. Example output: Please type a number: 7 The number is prime. The program checked 5 divisors. Please type a number: 2 The number is not prime. The program checked 1 divsor. Please type a number: 0 HOMEWORK EXERCISE