Presentation is loading. Please wait.

Presentation is loading. Please wait.

C# Programming Methods.

Similar presentations


Presentation on theme: "C# Programming Methods."— Presentation transcript:

1 C# Programming Methods

2 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

3 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

4 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 ); }

5 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: maximum is: 99.32

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

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

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

9 Calling Methods, cont.

10 Trace Method Invocation
i is now 5

11 Trace Method Invocation
j is now 2

12 Trace Method Invocation
invoke max(i, j)

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

14 Trace Method Invocation
declare variable result

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

16 Trace Method Invocation
result is now 5

17 Trace Method Invocation
return result, which is 5

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

19 Trace Method Invocation
Execute the print statement

20 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.

21 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.

22 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

23 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

24 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;

25 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

26 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)

27 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

28 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

29 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

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

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

32 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

33 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

34 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

35 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

36 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; }

37 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 ); }

38 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

39 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.

40 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


Download ppt "C# Programming Methods."

Similar presentations


Ads by Google