Chapter 5 - Methods Prentice Hall, Inc. All rights reserved.
|
|
- Emmeline Terry
- 5 years ago
- Views:
Transcription
1 1 Chapter 5 - Methods 2003 Prentice Hall, Inc. All rights reserved.
2 2 Introduction Modules Small pieces of a problem e.g., divide and conquer Facilitate design, implementation, operation and maintenance of large programs 2003 Prentice Hall, Inc. All rights reserved.
3 3 Program Modules in Java Modules in Java Methods Classes Java API provides several modules Programmers can also create modules e.g., programmer-defined methods Methods Invoked by a method call Returns a result to calling method (caller) Similar to a boss (caller) asking a worker (called method) to complete a task 2003 Prentice Hall, Inc. All rights reserved.
4 4 boss worker1 worker2 worker3 worker4 worker5 Fig. 6.1 Hiera rchica l boss-method/ worker-method rela tionship Prentice Hall, Inc. All rights reserved.
5 5 Math-Cla ss Methods Class java.lang.math Provides common mathematical calculations Calculate the square root of 900.0: Math.sqrt( ) Method sqrt belongs to class Math Dot (.) allows access to method sqrt The argument is located inside parentheses 2003 Prentice Hall, Inc. All rights reserved.
6 6 Methods Decla ra tions Methods Allow programmers to modularize programs Makes program development more manageable Software reusability Avoid repeating code Local variables Declared in method declaration Parameters Communicates information between methods via method calls 2003 Prentice Hall, Inc. All rights reserved.
7 7 import java.awt.container; import javax.swing.*; public class SquareIntegers extends JApplet { public void init() { JTextArea outputarea = new JTextArea(); Container container = getcontentpane(); container.add( outputarea ); int result; String output = ""; for ( int counter = 1; counter <= 10; counter++ ) { result = square( counter ); output += "The square of " + counter + " is " + result + "\n"; }
8 8 outputarea.settext( output ); } public int square( int y ) { return y * y; } }
9 Method Decla ra tions (cont.) 9 General format of method declaration: return-value-type method-name( parameter1, parameter2,, parametern ) { declarations and statements } Method can also return values: return expression; 2003 Prentice Hall, Inc. All rights reserved.
10 import java.awt.container; 10 import javax.swing.*; public class MaximumTest extends JApplet { // initialize applet by obtaining user input and creating GUI public void init() { // obtain user input String s1 = JOptionPane.showInputDialog( "Enter first floating-point value" ); String s2 = JOptionPane.showInputDialog( "Enter second floating-point value" ); String s3 = JOptionPane.showInputDialog( "Enter third floating-point value" ); // convert user input to double values double number1 = Double.parseDouble( s1 ); double number2 = Double.parseDouble( s2 ); double number3 = Double.parseDouble( s3 ); double max = maximum( number1, number2, number3 ); // method call // create JTextArea to display results JTextArea outputarea = new JTextArea(); // display numbers and maximum value outputarea.settext( "number1: " + number1 + "\nnumber2: " + number2 + "\nnumber3: " + number3 + "\nmaximum is: " + max );
11 11 Container container = getcontentpane(); container.add( outputarea ); } public double maximum( double x, double y, double z ) { return Math.max( x, Math.max( y, z ) ); } }
12 Argument Promotion 12 Coercion of arguments Forcing arguments to appropriate type to pass to method e.g., System.out.println( Math.sqrt( 4 ) ); Evaluates Math.sqrt( 4 ) Then evaluates System.out.println() Promotion rules Specify how to convert types without data loss 2003 Prentice Hall, Inc. All rights reserved.
13 13 Type Valid promotions double None float double long float or double int long, float or double char int, long, float or double short int, long, float or double byte short, int, long, float or double boolean None (boolean values are not considered to be numbers in Java) 2003 Prentice Hall, Inc. All rights reserved.
14 Java API Packages 14 Packages Classes grouped into categories of related classes Promotes software reuse import statements specify classes used in Java programs e.g., import javax.swing.japplet; 2003 Prentice Hall, Inc. All rights reserved.
15 Ra ndom-number Genera tion 15 Java random-number generators Math.random() ( int ) ( Math.random() * 6 ) Produces integers from 0-5 Use a seed for different random-number sequences 2003 Prentice Hall, Inc. All rights reserved.
16 1 // Fig. 6.7: RandomIntegers.java 2 // Shifted, scaled random integers. 3 import javax.swing.joptionpane; 4 5 public class RandomIntegers { 6 7 public static void main( String args[] ) 8 { 9 int value; 10 String output = ""; // loop 20 times 13 for ( int counter = 1; counter <= 20; counter++ ) { // pick random integer between 1 and 6 16 value = 1 + ( int ) ( Math.random() * 6 ); output += value + " "; // append value to output // if counter divisible by 5, append newline to String output 21 if ( counter % 5 == 0 ) 22 output += "\n"; } // end for 25 Produce integers in range 1-6 Math.random returns doubles. We cast the double as an int Prentice Hall, Inc. All rights reserved.
17 26 JOptionPane.showMessageDialog( null, output, 27 "20 Random Numbers from 1 to 6", 28 JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); // terminate application } // end main } // end class RandomIntegers 17 RandomIntegers. java 2003 Prentice Hall, Inc. All rights reserved.
18 1 // Fig. 6.8: RollDie.java 2 // Roll a six-sided die 6000 times. 3 import javax.swing.*; 4 5 public class RollDie { 6 7 public static void main( String args[] ) 8 { 9 int frequency1 = 0, frequency2 = 0, frequency3 = 0, 10 frequency4 = 0, frequency5 = 0, frequency6 = 0, face; // summarize results 13 for ( int roll = 1; roll <= 6000; roll++ ) { 14 face = 1 + ( int ) ( Math.random() * 6 ); // determine roll value and increment appropriate counter 17 switch ( face ) { case 1: 20 ++frequency1; 21 break; case 2: 24 ++frequency2; 25 break; case 3: 28 ++frequency3; 29 break; 30 Produce integers in range 1-6 Increment appropriate frequency counter, depending on randomly generated number Prentice Hall, Inc. All rights reserved.
19 31 case 4: 32 ++frequency4; 33 break; case 5: 36 ++frequency5; 37 break; case 6: 40 ++frequency6; 41 break; } // end switch } // end for JTextArea outputarea = new JTextArea(); outputarea.settext( "Face\tFrequency" + "\n1\t" + frequency "\n2\t" + frequency2 + "\n3\t" + frequency "\n4\t" + frequency4 + "\n5\t" + frequency "\n6\t" + frequency6 ); JOptionPane.showMessageDialog( null, outputarea, 55 "Rolling a Die 6000 Times", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); // terminate application } // end main } // end class RollDie 2003 Prentice Hall, Inc. All rights reserved. 19
20 20 Scope of Declarations Scope Portion of the program that can reference an entity by its name Basic scope rules Scope of a parameter declaration Scope of a local-variable declaration Scope of a label in a labeled break or continue statement Scope of a local-variable declaration that appears in the initialization section of a for statement s header Scope of a method or field of a class 2003 Prentice Hall, Inc. All rights reserved.
21 1 // Fig. 6.10: Scoping.java 2 // A scoping example. 3 import java.awt.container; 4 5 import javax.swing.*; 6 7 public class Scoping extends JApplet { 8 JTextArea outputarea; 9 10 // field that is accessible to all methods of this class 11 int x = 1; // create applet's GUI 14 public void init() 15 { 16 outputarea = new JTextArea(); 17 Container container = getcontentpane(); 18 container.add( outputarea ); } // end method init // method start called after init completes; start calls 23 // methods uselocal and usefield 24 public void start() 25 { Field x has class scope Local variable x has block scope Method start uses local variable x 26 int x = 5; // local variable in method start that shadows field x outputarea.append( "local x in start is " + x ); Prentice Hall, Inc. All rights reserved.
22 30 uselocal(); // uselocal has local x 31 usefield(); // useinstance uses Scoping's field x 32 uselocal(); // uselocal reinitializes local x 33 usefield(); // Scoping's field x retains its value outputarea.append( "\n\nlocal x in start is " + x ); } // end method start Re-create variable x and // uselocal creates and initializes initialize local it to 25 variable x during each call 40 public void uselocal() 41 { 42 int x = 25; // initialized each time uselocal is called outputarea.append( "\n\nlocal x in uselocal is " + x + 45 " after entering uselocal" ); 46 ++x; 47 outputarea.append( "\nlocal x in uselocal is " + x + 48 " before exiting uselocal" ); } // end method uselocal 51 Method uselocal uses local variable x Prentice Hall, Inc. All rights reserved.
23 52 // usefield modifies Scoping's field x during each call 53 public void usefield() 54 { 55 outputarea.append( "\n\nfield x is " + x + 56 " on entering usefield" ); 57 x *= 10; 58 outputarea.append( "\nfield x is " + x + 59 " on exiting usefield" ); } // end method useinstance } // end class Scoping Method usefield uses field x Prentice Hall, Inc. All rights reserved.
24 Methods of Cla ss JApplet 24 Method public void init() When the method is called and its purpose This method is called once by the applet container when an applet is loaded for execution. It performs initialization of an applet. Typical actions performed here are initializing fields, creating GUI components, loading sounds to play, loading images to display. public void start() This method is called after the init method completes execution. In addition, if the browser user visits another Web site and later returns to the HTML page on which the applet resides, method start is called again. The method performs any tasks that must be completed when the applet is loaded for the first time and that must be performed every time the HTML page on which the applet resides is revisited. public void This drawing method is called after the init method completes execution and the start method has paint( Graphics started. It is also called every time the applet needs to be repainted. For example, if the user covers g ) the applet with another open window on the screen and later uncovers the applet, the paint method is called. Typical actions performed here involve drawing with the Graphics object g that is passed to the paint method by the applet container. public void stop() public void destroy() This method is called when the applet should stop executing normally, when the user of the browser leaves the HTML page on which the applet resides. The method performs any tasks that are required to suspend the applet s execution. Typical actions performed here are to stop execution of animations and threads. This method is called when the applet is being removed from memory normally, when the user of the browser exits the browsing session (i.e., closes all browser windows). The method performs any tasks that are required to destroy resources allocated to the applet.
25 25 Method Overloa ding Method overloading Several methods of the same name Different parameter set for each method Number of parameters Parameter types 2003 Prentice Hall, Inc. All rights reserved.
26 1 // Fig. 6.12: MethodOverload.java 2 // Using overloaded methods 3 import java.awt.container; 4 5 import javax.swing.*; 6 7 public class MethodOverload extends JApplet { 8 9 // create GUI and call each square method 10 public void init() 11 { 12 JTextArea outputarea = new JTextArea(); 13 Container container = getcontentpane(); 14 container.add( outputarea ); outputarea.settext( "The square of integer 7 is " + square( 7 ) + 17 "\nthe square of double 7.5 is " + square( 7.5 ) ); } // end method init Method square receives an int as an argument // square method with int argument 22 public int square( int intvalue ) 23 { 24 System.out.println( "Called square with int argument: " + 25 intvalue ); return intvalue * intvalue; } // end method square with int argument Prentice Hall, Inc. All rights reserved.
27 31 // square method with double argument 32 public double square( double doublevalue ) 33 { 34 System.out.println( "Called square with double argument: " + 35 doublevalue ); return doublevalue * doublevalue; } // end method square with double argument } // end class MethodOverload Overloaded method square receives a double as an argument 27 Called square with int argument: 7 Called square with double argument: Prentice Hall, Inc. All rights reserved.
28 1 // Fig. 6.13: MethodOverload.java 2 // Overloaded methods with identical signatures. 3 import javax.swing.japplet; 4 5 public class MethodOverload extends JApplet { 6 7 // declaration of method square with int argument 8 public int square( int x ) 9 { 10 return x * x; 11 } // second declaration of method square 14 // with int argument causes syntax error 15 public double square( int y ) 16 { 17 return y * y; 18 } } // end class MethodOverload Compiler cannot distinguish between methods with identical names and parameter sets 28 MethodOverload.java:15: square(int) is already defined in MethodOverload public double square( int y ) ^ 1 error 2003 Prentice Hall, Inc. All rights reserved.
29 29 Recursion Recursive method Calls itself (directly or indirectly) through another method Method knows how to solve only a base case Method divides problem Base case Simpler problem Method now divides simpler problem until solvable Recursive call Recursive step 2003 Prentice Hall, Inc. All rights reserved.
30 30 5! 5! Final value = 120 5! = 5 * 24 = 120 is returned 5 * 4! 5 * 4! 4! = 4 * 6 = 24 is returned 4 * 3! 4 * 3! 3! = 3 * 2 = 6 is returned 3 * 2! 3 * 2! 2! = 2 * 1 = 2 is returned 2 * 1! 1 2 * 1! 1 1 returned (a) Sequence of recursive calls. (b) Values returned from each recursive call Prentice Hall, Inc. All rights reserved.
31 1 // Fig. 6.15: FactorialTest.java 2 // Recursive factorial method. 3 import java.awt.*; 4 5 import javax.swing.*; 6 7 public class FactorialTest extends JApplet { 8 JTextArea outputarea; 9 10 // create GUI and calculate factorials of public void init() 12 { 13 outputarea = new JTextArea(); Container container = getcontentpane(); 16 container.add( outputarea ); // calculate the factorials of 0 through for ( long counter = 0; counter <= 10; counter++ ) 20 outputarea.append( counter + "! = " + 21 factorial( counter ) + "\n" ); } // end method init 24 Invoke method factorial Prentice Hall, Inc. All rights reserved.
32 25 // recursive declaration of method factorial 26 public long factorial( long number ) 27 { 28 // base case 29 if ( number <= 1 ) 30 return 1; // recursive step 33 else 34 return number * factorial( number - 1 ); } // end method factorial } // end class FactorialTest Test for base case (method factorial can solve base case) Else return simpler problem that method factorial might solve in next recursive call Prentice Hall, Inc. All rights reserved.
33 33 Recursion vs. Itera tion Iteration Uses repetition structures (for, while or do while) Repetition through explicitly use of repetition structure Terminates when loop-continuation condition fails Controls repetition by using a counter Recursion Uses selection structures (if, if else or switch) Repetition through repeated method calls Terminates when base case is satisfied Controls repetition by dividing problem into simpler one 2003 Prentice Hall, Inc. All rights reserved.
34 34 Recursion vs. Itera tion (cont.) Recursion More overhead than iteration More memory intensive than iteration Can also be solved iteratively Often can be implemented with only a few lines of code 2003 Prentice Hall, Inc. All rights reserved.
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 informationMethods (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 informationPart 8 Methods. scope of declarations method overriding method overloading recursions
Part 8 Methods scope of declarations method overriding method overloading recursions Modules Small pieces of a problem e.g., divide and conquer 6.1 Introduction Facilitate design, implementation, operation
More informationChapter 6 - Methods Prentice Hall. All rights reserved.
Chapter 6 - Methods 1 Outline 6.1 Introduction 6.2 Program Modules in Java 6.3 Math Class Methods 6.4 Methods 6.5 Method Definitions 6.6 Argument Promotion 6.7 Java API Packages 6.8 Random-Number Generation
More informationMethods: 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 informationArrays (Deitel chapter 7)
Arrays (Deitel chapter 7) Plan Arrays Declaring and Creating Arrays Examples Using Arrays References and Reference Parameters Passing Arrays to Methods Sorting Arrays Searching Arrays: Linear Search and
More informationChapter 3 - Functions
Chapter 3 - Functions 1 Outline 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3.4 Functions 3.5 Function Definitions 3.6 Function Prototypes 3.7 Header Files 3.8 Random Number
More informationChapter 6 Arrays and Strings Prentice Hall, Inc. All rights reserved.
1 Chapter 6 Arrays and Strings Introduction 2 Arrays Data structures Related data items of same type Reference type Remain same size once created Fixed-length entries 3 Name of array (note that all elements
More informationArrays Introduction. Group of contiguous memory locations. Each memory location has same name Each memory location has same type
Array Arrays Introduction Group of contiguous memory locations Each memory location has same name Each memory location has same type Remain same size once created Static entries 1 Name of array (Note that
More informationObject Oriented Methods : Deeper Look Lecture Three
University of Babylon Collage of Computer Assistant Lecturer : Wadhah R. Baiee Experience has shown that the best way to develop and maintain a large program is to construct it from small, simple pieces,
More informationFunctions. Computer System and programming in C Prentice Hall, Inc. All rights reserved.
Functions In general, functions are blocks of code that perform a number of pre-defined commands to accomplish something productive. You can either use the built-in library functions or you can create
More informationThe first applet we shall build will ask the user how many times the die is to be tossed. The request is made by utilizing a JoptionPane input form:
Lecture 5 In this lecture we shall discuss the technique of constructing user-defined methods in a class. The discussion will be centered about an experiment of tossing a die a specified number of times.
More informationDr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)
Lecture 9 Functions Dr M Kasim A Jalil Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson) Objectives In this chapter, you will learn: To understand how to construct programs modularly
More informationChapter 4 Control Structures: Part 2
Chapter 4 Control Structures: Part 2 1 2 Essentia ls of Counter-Controlled Repetition Counter-controlled repetition requires: Control variable (loop counter) Initial value of the control variable Increment/decrement
More informationFunctions. Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.
Functions Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan 2009 Fall Outline 5.1 Introduction 5.3 Math Library Functions 5.4 Functions 5.5
More informationMethods: A Deeper Look Pearson Education, Inc. All rights reserved.
1 6 Methods: A Deeper Look 2 The greatest invention of the nineteenth century was the invention of the method of invention. Alfred North Whitehead Call me Ishmael. Herman Melville When you call me that,
More informationJava Applets. Last Time. Java Applets. Java Applets. First Java Applet. Java Applets. v We created our first Java application
Last Time v We created our first Java application v What are the components of a basic Java application? v What GUI component did we use in the examples? v How do we write to the standard output? v An
More informationOutline. 7.1 Introduction. 7.2 Arrays. 7.2 Arrays
jhtp5_07.fm Page 279 Wednesday, November 20, 2002 12:44 PM 7 Arrays Objectives To introduce the array data structure. To understand the use of arrays to store, sort and search lists and tables of values.
More informationCHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad
CHAPTER 4 FUNCTIONS Dr. Shady Yehia Elmashad Outline 1. Introduction 2. Program Components in C++ 3. Math Library Functions 4. Functions 5. Function Definitions 6. Function Prototypes 7. Header Files 8.
More informationCS 335 Lecture 02 Java Programming
1 CS 335 Lecture 02 Java Programming Programming in Java Define data Calculate using data Output result Java is object-oriented: Java program must: Merge data and functions into object Invoke functions
More informationAn applet is a program written in the Java programming language that can be included in an HTML page, much in the same way an image is included in a
CBOP3203 An applet is a program written in the Java programming language that can be included in an HTML page, much in the same way an image is included in a page. When you use a Java technology-enabled
More informationC 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 informationChapter 3 - Functions
Chapter 3 - Functions 1 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3.4 Functions 3.5 Function Definitions 3.6 Function Prototypes 3.7 Header Files 3.8 Random Number Generation
More informationControl Structures (Deitel chapter 4,5)
Control Structures (Deitel chapter 4,5) 1 2 Plan Control Structures ifsingle-selection Statement if else Selection Statement while Repetition Statement for Repetition Statement do while Repetition Statement
More informationCS110D: PROGRAMMING LANGUAGE I
CS110D: PROGRAMMING LANGUAGE I Computer Science department Lecture 7&8: Methods Lecture Contents What is a method? Static methods Declaring and using methods Parameters Scope of declaration Overloading
More informationChapter 3 - Functions. Chapter 3 - Functions. 3.1 Introduction. 3.2 Program Components in C++
Chapter 3 - Functions 1 Chapter 3 - Functions 2 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3. Functions 3.5 Function Definitions 3.6 Function Prototypes 3. Header Files 3.8
More informationChapter 3 - Functions
Chapter 3 - Functions 1 Outline 3.1 Introduction 3.2 Progra m Components in C++ 3.3 Ma th Libra ry Func tions 3.4 Func tions 3.5 Func tion De finitions 3.6 Func tion Prototypes 3.7 He a de r File s 3.8
More informationJava 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 informationFunctions and Recursion
Functions and Recursion 1 Outline Introduction Program Components in C++ Math Library Functions Functions Function Definitions Function Prototypes Header Files Random Number Generation Example: A Game
More informationMethods: A Deeper Look
www.thestudycampus.com Methods: A Deeper Look 6.1 Introduction 6.2 Program Modules in Java 6.3 static Methods, static Fields and ClassMath 6.4 Declaring Methods with Multiple Parameters 6.5 Notes on Declaring
More informationChapter 6 SINGLE-DIMENSIONAL ARRAYS
Chapter 6 SINGLE-DIMENSIONAL ARRAYS Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk What is an Array? A single array variable can reference
More informationCS 335 Java Programming Controls. Fall 2007
CS 335 Java Programming Controls Fall 2007 Java Control Structures Selection: If, If/Else, Switch Repetition (looping): While, For, Do/While Assignment: Expressions, increment/decrement Java Reserved Words
More informationChapter 5 Control Structures: Part 2
Chapter 5 Control Structures: Part 2 Essentials of Counter-Controlled Repetition Counter-controlled repetition requires: Name of control variable (loop counter) Initial value of control variable Increment/decrement
More informationLecture 04 FUNCTIONS AND ARRAYS
Lecture 04 FUNCTIONS AND ARRAYS 1 Motivations Divide hug tasks to blocks: divide programs up into sets of cooperating functions. Define new functions with function calls and parameter passing. Use functions
More informationChapter 3 - Introduction to Java Applets
1 Chapter 3 - Introduction to Java Applets 2 Introduction Applet Program that runs in appletviewer (test utility for applets) Web browser (IE, Communicator) Executes when HTML (Hypertext Markup Language)
More informationCT 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 informationRoad Map. Introduction to Java Applets Review applets that ship with JDK Make our own simple applets
Java Applets Road Map Introduction to Java Applets Review applets that ship with JDK Make our own simple applets Introduce inheritance Introduce the applet environment html needed for applets Reading:
More informationCSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU
CSE101-lec#12 Designing Structured Programs Introduction to Functions Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU Outline Designing structured programs in C: Counter-controlled repetition
More informationLecture 04 FUNCTIONS AND ARRAYS
Lecture 04 FUNCTIONS AND ARRAYS 1 Motivations Divide hug tasks to blocks: divide programs up into sets of cooperating functions. Define new functions with function calls and parameter passing. Use functions
More informationBIL 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 informationCSE123. Program Design and Modular Programming Functions 1-1
CSE123 Program Design and Modular Programming Functions 1-1 5.1 Introduction A function in C is a small sub-program performs a particular task, supports the concept of modular programming design techniques.
More informationFundamentals of Programming Session 13
Fundamentals of Programming Session 13 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2014 These slides have been created using Deitel s slides Sharif University of Technology Outlines
More informationC Programming for Engineers Functions
C Programming for Engineers Functions ICEN 360 Spring 2017 Prof. Dola Saha 1 Introduction Real world problems are larger, more complex Top down approach Modularize divide and control Easier to track smaller
More informationLecture #6-7 Methods
Lecture #6-7 s 1. a. group of statements designed to perform a specific function b. may be reused many times i. in a particular program or ii. in multiple programs 2. Examples from the Java Library a.
More informationCS110: 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 informationC++ How to Program, 9/e by Pearson Education, Inc. All Rights Reserved.
C++ How to Program, 9/e 1992-2014 by Pearson Education, Inc. Experience has shown that the best way to develop and maintain a large program is to construct it from small, simple pieces, or components.
More informationFunctions and Recursion
Functions and Recursion 1 Storage Classes Scope Rules Functions with Empty Parameter Lists Inline Functions References and Reference Parameters Default Arguments Unary Scope Resolution Operator Function
More informationFunctions. Systems Programming Concepts
Functions Systems Programming Concepts Functions Simple Function Example Function Prototype and Declaration Math Library Functions Function Definition Header Files Random Number Generator Call by Value
More informationIT 374 C# and Applications/ IT695 C# Data Structures
IT 374 C# and Applications/ IT695 C# Data Structures Module 2.5: Methods A Deeper Look Xianrong (Shawn) Zheng Spring 2017 1 Outline static Methods, static Variables, and Class Math Methods with Multiple
More informationFunctions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single
Functions in C++ Problem-Solving Procedure With Modular Design: Program development steps: Analyze the problem Develop a solution Code the solution Test/Debug the program C ++ Function Definition: A module
More information엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED
엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED Outline - Function Definitions - Function Prototypes - Data
More informationThe Math Class. Using various math class methods. Formatting the values.
The Math Class Using various math class methods. Formatting the values. The Math class is used for mathematical operations; in our case some of its functions will be used. In order to use the Math class,
More informationQ1 Q2 Q3 Q4 Q5 Total 1 * 7 1 * 5 20 * * Final marks Marks First Question
Page 1 of 6 Template no.: A Course Name: Computer Programming1 Course ID: Exam Duration: 2 Hours Exam Time: Exam Date: Final Exam 1'st Semester Student no. in the list: Exam pages: Student's Name: Student
More informationPace University. Fundamental Concepts of CS121 1
Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction
More informationKey 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 informationMethods. Bok, Jong Soon
Methods Bok, Jong Soon javaexpert@nate.com www.javaexpert.co.kr Methods Enable you to separate statements into code blocks. Can be called whenever appropriate. Can invoke each other. Can call themselves(recursion)
More information142
Scope Rules Thus, storage duration does not affect the scope of an identifier. The only identifiers with function-prototype scope are those used in the parameter list of a function prototype. As mentioned
More informationIntroduction to Programming Using Java (98-388)
Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;
More informationC Functions. Object created and destroyed within its block auto: default for local variables
1 5 C Functions 5.12 Storage Classes 2 Automatic storage Object created and destroyed within its block auto: default for local variables auto double x, y; Static storage Variables exist for entire program
More informationC++ 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 informationCST141 Thinking in Objects Page 1
CST141 Thinking in Objects Page 1 1 2 3 4 5 6 7 8 Object-Oriented Thinking CST141 Class Abstraction and Encapsulation Class abstraction is the separation of class implementation from class use It is not
More informationhttps://asd-pa.perfplusk12.com/admin/admin_curric_maps_display.aspx?m=5507&c=618&mo=18917&t=191&sy=2012&bl...
Page 1 of 13 Units: - All - Teacher: ProgIIIJavaI, CORE Course: ProgIIIJavaI Year: 2012-13 Intro to Java How is data stored by a computer system? What does a compiler do? What are the advantages of using
More informationCS 61B Data Structures and Programming Methodology. June David Sun
CS 61B Data Structures and Programming Methodology June 25 2008 David Sun Announcements Visit 387 Soda to arrange for after hours access to Soda Hall. Computer Science Undergraduate Association event:
More informationCS313D: ADVANCED PROGRAMMING LANGUAGE
CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science Department Lecture 3: C# language basics Lecture Contents 2 C# basics Conditions Loops Methods Arrays Dr. Amal Khalifa, Spr 2015 3 Conditions and
More informationTypes and Expressions. Chapter 3
Types and Expressions Chapter 3 Chapter Contents 3.1 Introductory Example: Einstein's Equation 3.2 Primitive Types and Reference Types 3.3 Numeric Types and Expressions 3.4 Assignment Expressions 3.5 Java's
More informationObject-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018
Object-oriented programming 1 and data-structures CS/ENGRD 2110 SUMMER 2018 Lecture 1: Types and Control Flow http://courses.cs.cornell.edu/cs2110/2018su Lecture 1 Outline 2 Languages Overview Imperative
More informationA variable is a name for a location in memory A variable must be declared
Variables A variable is a name for a location in memory A variable must be declared, specifying the variable's name and the type of information that will be held in it data type variable name int total;
More information34. Recursion. Java. Summer 2008 Instructor: Dr. Masoud Yaghini
34. Recursion Java Summer 2008 Instructor: Dr. Masoud Yaghini Outline Introduction Example: Factorials Example: Fibonacci Numbers Recursion vs. Iteration References Introduction Introduction Recursion
More informationCopyright 1999 by Deitel & Associates, Inc. All Rights Reserved.
CHAPTER 2 1 2 1 // Fig. 2.1: Welcome1.java 2 // A first program in Java 3 4 public class Welcome1 { 5 public static void main( String args[] ) 6 { 7 System.out.println( "Welcome to Java Programming!" );
More informationProgramming for Engineers Functions
Programming for Engineers Functions ICEN 200 Spring 2018 Prof. Dola Saha 1 Introduction Real world problems are larger, more complex Top down approach Modularize divide and control Easier to track smaller
More informationC: How to Program. Week /Apr/16
C: How to Program Week 8 2006/Apr/16 1 Storage class specifiers 5.11 Storage Classes Storage duration how long an object exists in memory Scope where object can be referenced in program Linkage specifies
More informationCS 106 Introduction to Computer Science I
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
More informationReview. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char
Review Primitive Data Types & Variables int, long float, double boolean char String Mathematical operators: + - * / % Comparison: < > = == 1 1.3 Conditionals and Loops Introduction to Programming in
More informationCHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad
CHAPTER 4 FUNCTIONS Dr. Shady Yehia Elmashad Outline 1. Introduction 2. Program Components in C++ 3. Math Library Functions 4. Functions 5. Function Definitions 6. Function Prototypes 7. Header Files 8.
More informationName :. Roll No. :... Invigilator s Signature : INTRODUCTION TO PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70
Name :. Roll No. :..... Invigilator s Signature :.. 2011 INTRODUCTION TO PROGRAMMING Time Allotted : 3 Hours Full Marks : 70 The figures in the margin indicate full marks. Candidates are required to give
More informationIntroduction to Programming
Introduction to Programming session 9 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2010 These slides are created using Deitel s slides Sahrif University of Technology Outlines
More information12/22/11. } Rolling a Six-Sided Die. } Fig 6.7: Rolling a Six-Sided Die 6,000,000 Times
} Rolling a Six-Sided Die face = 1 + randomnumbers.nextint( 6 ); The argument 6 called the scaling factor represents the number of unique values that nextint should produce (0 5) This is called scaling
More informationFunctions. Introduction :
Functions Introduction : To develop a large program effectively, it is divided into smaller pieces or modules called as functions. A function is defined by one or more statements to perform a task. In
More informationUnit 1 Lesson 4. Introduction to Control Statements
Unit 1 Lesson 4 Introduction to Control Statements Essential Question: How are control loops used to alter the execution flow of a program? Lesson 4: Introduction to Control Statements Objectives: Use
More informationSun ONE Integrated Development Environment
DiveIntoSunONE.fm Page 197 Tuesday, September 24, 2002 8:49 AM 5 Sun ONE Integrated Development Environment Objectives To be able to use Sun ONE to create, compile and execute Java applications and applets.
More informationCourse PJL. Arithmetic Operations
Outline Oman College of Management and Technology Course 503200 PJL Handout 5 Arithmetic Operations CS/MIS Department 1 // Fig. 2.9: Addition.java 2 // Addition program that displays the sum of two numbers.
More informationFunctions and an Introduction to Recursion Pearson Education, Inc. All rights reserved.
1 6 Functions and an Introduction to Recursion 2 Form ever follows function. Louis Henri Sullivan E pluribus unum. (One composed of many.) Virgil O! call back yesterday, bid time return. William Shakespeare
More informationDefining Classes and Methods
Defining Classes and Methods Chapter 4 Chapter 4 1 Basic Terminology Objects can represent almost anything. A class defines a kind of object. It specifies the kinds of data an object of the class can have.
More informationIntroduction 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 informationUnit 7. Functions. Need of User Defined Functions
Unit 7 Functions Functions are the building blocks where every program activity occurs. They are self contained program segments that carry out some specific, well defined task. Every C program must have
More informationJVM (java) compiler. A Java program is either a library of static methods (functions) or a data type definition
Programming Model Basic Structure of a Java Program The Java workflow editor (Code) P.java compiler (javac) P.class JVM (java) output A Java program is either a library of static methods (functions) or
More information6.5 Function Prototypes and Argument Coercion
6.5 Function Prototypes and Argument Coercion 32 Function prototype Also called a function declaration Indicates to the compiler: Name of the function Type of data returned by the function Parameters the
More informationPROGRAMMING FUNDAMENTALS
PROGRAMMING FUNDAMENTALS Q1. Name any two Object Oriented Programming languages? Q2. Why is java called a platform independent language? Q3. Elaborate the java Compilation process. Q4. Why do we write
More informationObjectives of CS 230. Java portability. Why ADTs? 8/18/14
http://cs.wellesley.edu/~cs230 Objectives of CS 230 Teach main ideas of programming Data abstraction Modularity Performance analysis Basic abstract data types (ADTs) Make you a more competent programmer
More informationA Foundation for Programming
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
More informationChapter 3 Function Overloading
Chapter 3 Function Overloading Function Overloading. Calling Overloaded Function. Function Overloading When Several Function declaration are specified for a single function name in the same scope, the
More informationcis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1
topics: introduction to java, part 1 cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 cis20.1-fall2007-sklar-leci.2 1 Java. Java is an object-oriented language: it is
More informationChapter 4 Introduction to Control Statements
Introduction to Control Statements Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives 2 How do you use the increment and decrement operators? What are the standard math methods?
More informationegrapher Language Reference Manual
egrapher Language Reference Manual Long Long: ll3078@columbia.edu Xinli Jia: xj2191@columbia.edu Jiefu Ying: jy2799@columbia.edu Linnan Wang: lw2645@columbia.edu Darren Chen: dsc2155@columbia.edu 1. Introduction
More informationFunctions. Functions are everywhere in C. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
1 Functions Functions are everywhere in C Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Introduction Function A self-contained program segment that carries
More informationObject-Based Programming (Deitel chapter 8)
Object-Based Programming (Deitel chapter 8) 1 Plan 2 Introduction Implementing a Time Abstract Data Type with a Class Class Scope Controlling Access to Members Referring to the Current Object s Members
More informationC Functions Pearson Education, Inc. All rights reserved.
1 5 C Functions 2 Form ever follows function. Louis Henri Sullivan E pluribus unum. (One composed of many.) Virgil O! call back yesterday, bid time return. William Shakespeare Call me Ishmael. Herman Melville
More informationC++ PROGRAMMING SKILLS Part 3 User-Defined Functions
C++ PROGRAMMING SKILLS Part 3 User-Defined Functions Introduction Function Definition Void function Global Vs Local variables Random Number Generator Recursion Function Overloading Sample Code 1 Functions
More informationChapter 6 Introduction to Defining Classes
Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of
More informationJava How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.
Java How to Program, 10/e Education, Inc. All Rights Reserved. Each class you create becomes a new type that can be used to declare variables and create objects. You can declare new classes as needed;
More information