C# Programming Methods.

Slides:



Advertisements
Similar presentations
BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
Advertisements

C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
1 Classes, Encapsulation, Methods and Constructors (Continued) Class definitions Instance data Encapsulation and Java modifiers Method declaration and.
Chapter 7: User-Defined Functions II
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
Methods. int month; int year class Month Defining Classes A class contains data declarations (static and instance variables) and method declarations (behaviors)
Chapter 5 Functions.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 5 Function Basics.
Chapter 6: User-Defined Functions I
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
COMP 110 Introduction to Programming Mr. Joshua Stough October 8, 2007.
Enhancing classes Visibility modifiers and encapsulation revisited
COMP 14 Introduction to Programming Mr. Joshua Stough February 28, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 8, 2005.
Chapter 6: Function. Scope of Variable A scope is a region of the program and broadly speaking there are three places, where variables can be declared:
 Introduction Introduction  Types of Function Types of Function  Library function Library function  User defined function User defined function 
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions and Recursion Outline Function Templates Recursion Example Using Recursion: The Fibonacci Series.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Functions.
Methods F Hello World! F Java program compilation F Introducing Methods F Declaring Methods F Calling Methods F Passing Parameters by value F Overloading.
Chapter 8: Arrays and Functions Department of Computer Science Foundation Year Program Umm Alqura University, Makkah Computer Programming Skills
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
Chapter 4 Introduction to Classes, Objects, Methods and strings
Jozef Goetz,  2002 Prentice Hall. All rights reserved. Credits:  Pearson Education, Inc. All rights reserved.
FUNCTIONS IN C++. DEFINITION OF A FUNCTION A function is a group of statements that together perform a task. Every C++ program has at least one function,
Structure Programming Lecture 8 Chapter 5&6 - Function – part I 12 December 2015.
Starting Out with C++ Early Objects ~~ 7 th Edition by Tony Gaddis, Judy Walters, Godfrey Muganda Modified for CMPS 1044 Midwestern State University 6-1.
 2001 Prentice Hall, Inc. All rights reserved. 1 Introduction to C# Part II.
Methods. Methods also known as functions or procedures. Methods are a way of capturing a sequence of computational steps into a reusable unit. Methods.
CSCI 3328 Object Oriented Programming in C# Chapter 6: Methods 1 Xiang Lian The University of Texas Rio Grande Valley Edinburg, TX 78539
1 Chapter 6 Methods. 2 Motivation Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.
C++ Class. © 2005 Pearson Addison-Wesley. All rights reserved 3-2 Abstract Data Types Figure 3.1 Isolated tasks: the implementation of task T does not.
Neal Stublen Breaking Down Tasks  Reduce large tasks into smaller units of code  Smaller units of code might be called any of the.
C++ Programming Lecture 13 Functions – Part V The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Functions Structured Programming. Topics to be covered Introduction to Functions Defining a function Calling a function Arguments, local variables and.
Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 6 - Methods Outline 6.1 Introduction 6.2 Program Modules in Java 6.3 Math -Class Methods 6.4.
1 CSC103: Introduction to Computer and Programming Lecture No 16.
Classes - Intermediate
Methods.
CHAPTER 4 FUNCTIONS Dr. Shady Yehia Elmashad. Outline 1.Introduction 2.Program Components in C++ 3.Math Library Functions 4.Functions 5.Function Definitions.
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
Lecture 02 Dr. Eng. Ibrahim El-Nahry Methods. 2 Learning Objectives Class Definition includes both methods and data properties Method Definition and Declaration.
Loops, Part II IT108 George Mason University. Indefinite Loop Don’t always have access to the number of iterations ahead of time If a condition (user-response,
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
INF120 Basics in JAVA Programming AUBG, COS dept Lecture 07 Title: Methods, part 1 Reference: MalikFarrell, chap 1, Liang Ch 5.
Functions + Overloading + Scope
Chapter 7: User-Defined Functions II
COMP 170 – Introduction to Object Oriented Programming
Value-Returning Functions
Chapter 5 Functions DDC 2133 Programming II.
JavaScript: Functions
User-Defined Functions
More Object Oriented Programming
Advanced Programming Chapter 7: Methods: A Deeper Look
Chapter 5 Function Basics
Group Status Project Status.
Classes, Encapsulation, Methods and Constructors (Continued)
Chapter 6 Methods.
Chapter 5 Methods.
CSCI 3328 Object Oriented Programming in C# Chapter 6: Methods
BBIT 212/ CISY 111 Object Oriented Programming (OOP)
Week 4 Lecture-2 Chapter 6 (Methods).
Functions Imran Rashid CTO at ManiWeber Technologies.
Corresponds with Chapter 5
Introduction to Methods and Interfaces
Chapter 6: Methods CS1: Java Programming Colorado State University
Presentation transcript:

C# Programming Methods

Writing a custom method Method Definitions Writing a custom method Header ReturnType Properties Name( Param1, Param2, … ) Body Contains the code of what the method does Contains the return value if necessary For uses call elsewhere in program Pass parameters if needed All methods must be defined inside of a class

write a program for Finding the maximum of three doubles using method Example write a program for Finding the maximum of three doubles using method

using System; class MaximumValue { static void Main( string[] args ) Console.Write( "Enter first floating-point value: " ); double number1 = Double.Parse( Console.ReadLine() ); Console.Write( "Enter second floating-point value: " ); double number2 = Double.Parse( Console.ReadLine() ); Console.Write( "Enter third floating-point value: " ); double number3 = Double.Parse( Console.ReadLine() ); double max = Maximum( number1, number2, number3 ); Console.WriteLine("\nmaximum is: " + max ); }

double Maximum( double x, double y, double z ) { return Math.Max( x, Math.Max( y, z ) ); } // end method Maximum } // end class MaximumValue Enter first floating-point value: 37.3 Enter second floating-point value: 99.32 Enter third floating-point value: 27.1928   maximum is: 99.32

Defining Methods A method is a collection of statements that are grouped together to perform an operation.

Defining Methods A method is a collection of statements that are grouped together to perform an operation.

Method Signature Method signature is the combination of the method name and the parameter list.

Calling Methods, cont.

Trace Method Invocation i is now 5

Trace Method Invocation j is now 2

Trace Method Invocation invoke max(i, j)

Trace Method Invocation invoke max(i, j) Pass the value of i to num1 Pass the value of j to num2

Trace Method Invocation declare variable result

Trace Method Invocation (num1 > num2) is true since num1 is 5 and num2 is 2

Trace Method Invocation result is now 5

Trace Method Invocation return result, which is 5

Trace Method Invocation return max(i, j) and assign the return value to k

Trace Method Invocation Execute the print statement

Example Create circle class that consists of the circle radius with methods to initialize the radius, calculate the circumference of the circle, and calculate the area of the circle.

Example Create rectangle class that consists of the length and width with methods to initialize the members, calculate the perimeter of the rectangle, and calculate the area of the rectangle.

Program Create class account to save personal account for a bank with interest. The class has account# and balance data The class has operations: deposit, withdraw, interest_earned {2% interest will be credited to account at end of each month if balance exceeds $10,000} and display_data

Passing Arguments: Call-By-Value vs. Call-By-Reference Passing by value Send a method a copy of the object Value-type variables are passed to methods by value When returned are always returned by value Set by value by default Passing by reference Send a method the actual reference point Causes the variable to be changed throughout the program Reference-type variables are passed to methods by reference When returned are always returned by reference To pass value-type variables by reference The ref keyword specifies by reference The out keyword means a called method will initialize it

using System; using System.Windows.Forms; class RefOutTest { static void SquareRef( ref int x ) { x = x * x; } static void SquareOut( out int x ) { x = 6; x = x * x; } static void Square( int x ){ x = x * x; } static void Main( string[] args ) { int y = 5; int z;

RefOutTest.cs string output1 = "" + y ; RefOutTest.SquareRef( ref y ); RefOutTest.SquareOut( out z ); string output2 = “ “ + y + "\n z: " + z + "\n\n\n"; RefOutTest.Square( y ); RefOutTest.Square( z ); string output3 = "y: " + y + "\nz: " + z + "\n\n"; MessageBox.Show( output1 + output2 + output3); } RefOutTest.cs

Example Create class account to save personal account for a bank. The class has account# and balance data The class has deposit( ), withdraw( ) and display_data( ) methods The main class create some account for some persons (as input data)

Recursion Recursive methods Methods that call themselves Directly Indirectly Call others methods which call it Continually breaks problem down to simpler forms Must converge in order to end recursion Each method call remains open (unfinished) Finishes each call and then finishes itself

Recap: Recursive Sum int Sum( int n ) { if ( n == 0 ) // base case return 0; else // recursive case return Sum( n-1 ) + n; } Sum(4) Sum(3) 3 6 Sum(2) 2 3 Sum(1) 1 Sum(0) 4 10

Recap: Local and Formal Variables Like a normal method call, each invocation of a recursive method has its own set of method variables, i.e., formal parameters and local variables void LotsOfPrints(int num) { int local = 2*num; if (num == 0) { } else { LotsOfPrints( num – 1 ); Console.WriteLine( local ); } LotsOfPrints(3): 2 4 6

using System; using System.Windows.Forms; public class FactorialTest { public FactorialTest() { for ( long i = 0; i <= 10; i++ ) outputLabel.Text += i + "! = " + Factorial( i ) + "\n"; }

public long Factorial( long number ) { if ( number <= 1 ) // base case return 1; else return number * Factorial( number - 1 ); }

Example Using Recursion: The Fibonacci Sequence F(n) = F(n - 1) + F(n - 2) Recursion is used to evaluate F(n) Complexity theory How hard computers need to work to perform algorithms

Example Write a 12-hour clock program that declares a clock class to store hours, minutes, seconds, A.M. and P.M. provide methods to perform the following tasks: Set hours, minutes, seconds to 00:00:00 by default Initialize hours, minutes, seconds, A.M. and P.M. from user entries Allow the clock to tick by advancing the seconds by one and at the same time correcting the hours and minutes for a 12-hour clock value of AM or PM Display the time in hours:minutes:seconds AM / PM format

Methods with the same name Method Overloading Methods with the same name Can have the same name but need different arguments Number of parameters, types of parameters, or order of parameters Variables passed must be different Either in type received or order sent Usually perform the same task On different data types A compiler distinguishes overloaded methods by their signatures A method’s signature is a combination of the method’s name and parameter types Note that return types are not considered part of the method’s signature

Method Overloading double TryMe (int x) { return x + .375; } Version 1 double TryMe (int x, double y) { return x*y; } Version 2 result = TryMe (25, 4.32) Invocation

More Examples double TryMe ( int x ) TryMe( 1 ); { return x + 5; } TryMe( 1 ); TryMe( 1.0 ); TryMe( 1.0, 2); TryMe( 1, 2); TryMe( 1.0, 2.0); double TryMe ( double x ) { return x * .375; } double TryMe (double x, int y) { return x + y; }

using System; using System.Windows.Forms; public class MethodOverload { public MethodOverload() { outputLabel.Text = "The square of integer 7 is " + Square( 7 ) + "\nThe square of double 7.5 is " + Square ( 7.5 ); }

public int Square ( int x ) { return x * x; } public double Square ( double y ) { return y * y; } static void Main() { new MethodOverload() ; } } // end of class MethodOverload

Example Coffee shop need a program to computerize its inventory. The data will be Coffee name, price, amount in stock, reorder level, barcode, sell by date. The operations on coffee are: prepare to enter stock, Display coffee data, check reorder level, change price, sell coffee.

Example Create a class Time that contains data members, hour, minute, second to store the time value, and sets hour, minute, second to zero, provide three methods for converting time to ( 24 hour ) and another one for converting time to (12 hour) and a function that sets the time to a certain value specified by three parameters