 2002 Prentice Hall. All rights reserved. 1 Passing Methods as Arguments public void BubbleSortArray( int[] array, Comparator Compare ) { for ( int pass.

Slides:



Advertisements
Similar presentations
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
Advertisements

Introduction to Computers and Programming Lecture 11: Introduction to Methods Professor: Evan Korth New York University.
 2003 Prentice Hall, Inc. All rights reserved. 7.1 Introduction Arrays –Data structures which reference one or more value –All items must have same data.
Introduction to Computers and Programming Introduction to Methods in Java.
Programming Based on Events
Math class methods & User defined methods Introduction to Computers and Programming in JAVA: V
 2006 Pearson Education, Inc. All rights reserved Generics Many slides modified by Prof. L. Lilien (even many without an explicit message). Slides.
Math class methods & User defined methods Math class methods Math.sqrt(4.0) Math.random() java.lang is the library/package that provides Math class methods.
 2002 Prentice Hall. All rights reserved. 1 Chapter 6 - Methods Outline Note: Inconsistent with textbook subsection numbering […] 6.14Recursion 6.15 Example.
CS Oct 2006 Chap 6. Functions General form; type Name ( parameters ) { … return value ; }
Review for Midterm 2 Nested loops & Math class methods & User defined methods.
 2002 Prentice Hall. All rights reserved. 1 Chapter 7 - Arrays Outline 7.1 Introduction 7.2 Arrays 7.3 Declaring and Allocating Arrays 7.4 Examples Using.
 2003 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Arrays Introduction to Computers and Programming in.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved COS240 O-O Languages AUBG,
Copyright © 2012 Pearson Education, Inc. Chapter 6 Modularizing Your Code with Methods.
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
 2002 Prentice Hall. All rights reserved. 1 Chapter 10 – Object-Oriented Programming: Polymorphism Outline 10.1 Introduction 10.2 Derived-Class-Object.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 9 Searching.
C# Event Processing Model Solving The Mystery. Agenda Introduction C# Event Processing Macro View Required Components Role of Each Component How To Create.
Describing algorithms in pseudo code To describe algorithms we need a language which is: – less formal than programming languages (implementation details.
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
Io package as Java’s basic I/O system continue’d.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 16.1 Test-Driving the Flag Quiz Application.
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved. Note: C How to Program, Chapter 22 is a copy of C++ How to Program Chapter.
Advanced Programming Array.
 2002 Prentice Hall. All rights reserved. 1 Week 2: Methods Questions about last week’s revision –C#.NET –.NET Framework –sequence, selection, repetition.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Passing Other Objects Strings are called immutable which means that once a String object stores a value, it never changes –recall when we passed a message.
1 CS1120: Recursion. 2 What is Recursion? A method is said to be recursive if the method definition contains a call to itself A recursive method is a.
 2002 Prentice Hall. All rights reserved. 1 Chapter 10 – Object-Oriented Programming: Polymorphism Outline 10.1 Introduction 10.2 Derived-Class-Object.
Carnegie Mellon University MSCF1 C#/.NET Basics 2 Some code is from “C# in a Nutshell”
Tuc Goodwin  Object and Component-Oriented Programming  Classes in C#  Scope and Accessibility  Methods and Properties  Nested.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Tutorial 17 – Flag Quiz Application Introducing One-Dimensional.
Procedural programming in Java Methods, parameters and return values.
Jozef Goetz,  2002 Prentice Hall. All rights reserved. Credits:  Pearson Education, Inc. All rights reserved.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
 2002 Prentice Hall. All rights reserved. 1 Introduction Polymorphism allows programmers to write: –Programs that handle a wide variety of related classes.
Module 8: Delegates and Events. Overview Delegates Multicast Delegates Events When to Use Delegates, Events, and Interfaces.
Computer Programming and Basic Software Engineering 9 Building Graphical User Interface Creating a Multiple-Form Interface.
Applications with Multiple Activities. Most applications will have more than one activity. The main activity is started when the application is started.
 2002 Prentice Hall. All rights reserved. 1 Chapter 10 – Object-Oriented Programming: Polymorphism Outline 10.1 Introduction 10.2 Derived-Class-Object.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
Interfaces and Inner Classes
From C++ to C# Part 5. Enums Similar to C++ Similar to C++ Read up section 1.10 of Spec. Read up section 1.10 of Spec.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 6 Functions.
Lecture 5 functions 1 © by Pearson Education, Inc. All Rights Reserved.
1 CSC103: Introduction to Computer and Programming Lecture No 19.
 2002 Prentice Hall. All rights reserved. 1 Chapter 10 – Object-Oriented Programming: Part 2 Outline 10.1Introduction 10.2 Derived-Class-Object to Base-Class-Object.
Arrays Chapter 6. Objectives learn about arrays and how to use them in Java programs learn how to use array parameters and how to define methods that.
IAP C# 2011 Lecture 2: Delegates, Lambdas, LINQ Geza Kovacs.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
 2002 Prentice Hall. All rights reserved. 1 Outline Mouse Event Handling Keyboard Event Handling Graphical User Interface Concepts:
 2002 Prentice Hall. All rights reserved. 1 Chapter 11 – [Object-Oriented Programming] Polymorphism, Interfaces & Operator Overloading Section [order.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
Subs and Functions Ch 6. Introduction VB.NET Procedures Sub Procedures Function Procedures Outline.
Jozef Goetz contribution, Credits go to  2014, 2011, 2009 Pearson Education, Inc. All rights reserved.  2002 Prentice Hall. All rights reserved.
Chapter  Array-like data structures  ArrayList  Queue  Stack  Hashtable  SortedList  Offer programming convenience for specific access.
Methods. Creating your own methods Java allows you to create custom methods inside its main body. public class Test { // insert your own methods right.
Lecture 03 Dr. Eng. Ibrahim El-Nahry Arrays. 2 Learning Objectives Introduction to Arrays Declaring and referencing arrays Initializing Arrays Arrays.
Lecture 4: Chapter 7 - Arrays Outline Declaring and Creating Arrays Examples Using Arrays References and Reference Parameters Passing Arrays to Methods.
Chapter 9 Programming Based on Events
INF230 Basics in C# Programming
Chapters 9, 10 – Object-Oriented Programming: Inheritance
Chapter 7 - Methods Outline Note: Inconsistent with textbook subsection numbering […] 7.13 Recursion […]
Questions from last lesson
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
6 Chapter Functions.
Delegates & Events 1.
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Lecture 03 & 04 Method and Arrays Jaeki Song.
Presentation transcript:

 2002 Prentice Hall. All rights reserved. 1 Passing Methods as Arguments public void BubbleSortArray( int[] array, Comparator Compare ) { for ( int pass = 0; pass < array.Length; pass++ ) for ( int i = 0; i < array.Length – 1-pass; i++ ) if ( Compare( array[ i ], array [ i + 1 ] ) ) // if Compare returns true, elements are out of order Swap( ref array[ i ], ref array[ i + 1 ] ); }

 2002 Prentice Hall. All rights reserved. 2 Delegates Sometimes useful to pass methods as arguments to other methods Example - sorting: –The same method can be used to sort in the ascending order and in the descending order –The only difference, when comparing elements: swap them only if the first is larger than the second for ascending order (e.g., …, 9, 3, … => …, 3, 9,… ) swap them only if the first is smaller than the second for descending order (e.g., …, 4, 7, … => …, 7, 4,… ) C# prohibits passing a method reference directly as an argument to another method. Must use delegates - delegate = a class that encapsulates sets of references to methods –Analogy: Prof. Ninu Atluri requires that students submit homeworks in yellow envelopes She allows a few students to use a single yellow envelope, but does not accept any homeworks not “encapsulated” by an envelope. Prof. Atluri “receiving method” (to which other methods’references are passed) homework method reference (passed to another method) yellow envelope delegate encapsulating references to passed methods Slide modified by L. Lilien

 2002 Prentice Hall. All rights reserved. 3 Delegates Delegates must be declared before use Delegate declaration specifies: the parameter-list the return type of the methods the delegate can refer to -E.g. delegate Comparator: public delegate bool Comparator( int element1, int element2 ); Delegates (delegate objects) are sets of references to methods –E.g., delegate Comparator - a set of references to 2 methods: SortAscending and SortDescending Slide modified by L. Lilien

 2002 Prentice Hall. All rights reserved. 4 Delegates Methods that can be referred to by a delegate, must have the same signature as the delegate –E.g.: public delegate bool Comparator( int el1, int el2 ); signature of Comparator is: (int, int) -> bool –Methods SortAscending or SortDescending referred to by Comparator must have the same signature ((int, int) -> bool) private bool SortAscending( int element1, int element2 ) private bool SortDescending( int element1, int element2 ) –Delegate instances can then be created to refer to the methods Slide modified by L. Lilien

 2002 Prentice Hall. All rights reserved. 5 Delegates Delegates can be passed to methods –E.g., delegate Comparator can be passed to method SortArray Once a delegate instance is created (below: instance of delegate Comparator is created with new), the method it refers to (below: SortAscending) can be invoked by the method (below: SortArray) to which the delegate passed it –E.g.: DelegateBubbleSort.SortArray( elementArray, new DelegateBubbleSort.Comparator( SortAscending ) ) The method to which a delegate passed methods can then invoke the methods the delegate object refers to –E.g., method SortArray can invoke method SortAscending to which delegate object Comparator refers to Slide modified by L. Lilien

 2002 Prentice Hall. All rights reserved. 6 Delegates Example – sorting Declare delegate Comparator : public delegate bool Comparator( int element1, int element2 ); // delegate signature: (int, int) -> bool –Use delegate Comparator to pass the appropriate comparison methods (SortAscending or SortDescending) to method SortArray: DelegateBubbleSort.SortArray( elementArray, new DelegateBubbleSort.Comparator( SortAscending ) ) [seen above] DelegateBubbleSort.SortArray(elementArray, new DelegateBubbleSort.Comparator( SortDescending ) ) [The passed methods (SortAscending and SortDescending) have the same signatures ((int, int) -> bool ) as delegate Comparator] Slide modified by L. Lilien

 2002 Prentice Hall. All rights reserved. 7 Delegates Types of delegates –singlecast delegate - contains one method created or derived from class Delegate (from System namespace) –multicast delegate - contains multiple methods created or derived from class MulticastDelegate (from System namespace) –E.g., Comparator is a singlecast delegate Because each instance contains a single method (either SortAscending or SortDescending) Delegates are very useful for event handling –We’ll see how they are used for mouse click events –Used for event handling - Chapters Not discussed in CS 1120 Slide modified by L. Lilien

 2002 Prentice Hall. All rights reserved. Outline 8 Example: Bubble Sort using forms and Delegates start

 2002 Prentice Hall. All rights reserved. Outline 9 DelegateBubbleSo rt.cs 1 // DelegateBubbleSort.cs 2 // Demonstrating delegates for sorting numbers. 3 4 public class DelegateBubbleSort 5 { 6 public delegate bool Comparator( int element1, 7 int element2 ); // Declare delegate Comparator, i.e., declare // signature for the method. // No implementation here (no body for Comparator). 8 9 // sort array using Comparator delegate 10 public static void SortArray( int[] array, 11 Comparator Compare ) // Reference to delegate Comparator // passed as a parameter to SortArray method. 12 { 13 for ( int pass = 0; pass < array.Length; pass++ ) for ( int i = 0; i < (array.Length – 1 – pass); i++ ) if ( Compare( array[ i ], array [ i + 1 ] ) ) // if Compare returns true, elements are out of order 18 Swap( ref array[ i ], ref array[ i + 1 ] ); 19 } // swap two elements 22 private static void Swap( ref int firstElement, 23 ref int secondElement ) 24 { 25 int hold = firstElement; 26 firstElement = secondElement; 27 secondElement = hold; 28 } 29 } Delegate Comparator definition declaration; defines a delegate to a method that takes two integer parameters and returns a boolean Method SortArray which takes an integer array and a Comparator delegate Call delegate method to compare array elements Method Swap, swaps the two arguments (passed by reference) Slide modified by L. Lilien

 2002 Prentice Hall. All rights reserved. Outline 10 BubbleSortForm.c s 1 // BubbleSortForm.cs 2 // Demonstrates bubble sort using delegates to determine 3 // the sort order. // Some thing will be magic for you (e.g. button click handling) 4 using System; 5 using System.Drawing; 6 using System.Collections; 7 using System.ComponentModel; 8 using System.Windows.Forms; 9 10 public class BubbleSortForm : System.Windows.Forms.Form 11 { 12 private System.Windows.Forms.TextBox originalTextBox; 13 private System.Windows.Forms.TextBox sortedTextBox; 14 private System.Windows.Forms.Button createButton; // 3 buttons 15 private System.Windows.Forms.Button ascendingButton; 16 private System.Windows.Forms.Button descendingButton; 17 private System.Windows.Forms.Label originalLabel; 18 private System.Windows.Forms.Label sortedLabel; private int[] elementArray = new int[ 10 ]; // create randomly generated set of numbers to sort 23 private void createButton_Click( object sender, 24 System.EventArgs e ) // magic here 25 { 26 // clear TextBoxes 27 originalTextBox.Clear(); 28 sortedTextBox.Clear(); // create random-number generator 31 Random randomNumber = new Random(); 32 Slide modified by L. Lilien

 2002 Prentice Hall. All rights reserved. Outline 11 BubbleSortForm.cs 33 // populate elementArray with random integers 34 for ( int i = 0; i < elementArray.Length; i++ ) 35 { 36 elementArray[ i ] = randomNumber.Next( 100 ); 37 originalTextBox.Text += elementArray[ i ] + "\r\n"; 38 } 39 } // delegate implementation for ascending sort // More precisely: implementation of SortAscending method which can be // passed to another method via Comparator delegate (matches its signature) 42 private bool SortAscending( int element1, int element2 ) 43 { 44 return element1 > element2; 45 } // sort randomly generated numbers in ascending order 48 private void ascendingButton_Click( object sender, 49 System.EventArgs e ) // magic here 50 { 51 // sort array, passing delegate for SortAscending 52 DelegateBubbleSort.SortArray( elementArray, 53 new DelegateBubbleSort.Comparator( 54 SortAscending ) ); DisplayResults(); 57 } // delegate implementation for desc. sort // More precisely: implementation of SortDescending method which can be // passed to another method via Comparator delegate (matches its signature) 60 private bool SortDescending( int element1, int element2 ) 61 { 62 return element1 < element2; 63 } 64 Method SortAscending returns true if the first argument is larger then the second; returns false otherwise Method SortDescending returns true if the first argument is smaller then the second; returns false otherwise To sort in ascending order, send a delegate for the SortAscending method to method SortArray Slide modified by L. Lilien

 2002 Prentice Hall. All rights reserved. Outline 12 BubbleSortForm.c s 65 // sort randomly generating numbers in descending order 66 private void descendingButton_Click( object sender, 67 System.EventArgs e ) // magic here 68 { 69 // sort array, passing delegate for SortDescending 70 DelegateBubbleSort.SortArray( elementArray, 71 new DelegateBubbleSort.Comparator( 72 SortDescending ) ); DisplayResults(); 75 } // display the sorted array in sortedTextBox 78 private void DisplayResults() 79 { 80 sortedTextBox.Clear(); foreach ( int element in elementArray ) 83 sortedTextBox.Text += element + "\r\n"; 84 } // main entry point for application 87 public static void Main( string[] args ) 88 { 89 Application.Run( new BubbleSortForm() ); // new instance waits for button click 90 } 91 } To sort in descending order, send a delegate to the SortDescending method to method SortArray Slide modified by L. Lilien

 2002 Prentice Hall. All rights reserved. Outline 13 BubbleSortForm.c s Program Output