Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Chapter 5: Methods FIntroducing Methods FDeclaring Methods FCalling Methods FLocal Variables in Methods FPass by Value FOverloading Methods FMethod.

Similar presentations


Presentation on theme: "1 Chapter 5: Methods FIntroducing Methods FDeclaring Methods FCalling Methods FLocal Variables in Methods FPass by Value FOverloading Methods FMethod."— Presentation transcript:

1

2 1 Chapter 5: Methods FIntroducing Methods FDeclaring Methods FCalling Methods FLocal Variables in Methods FPass by Value FOverloading Methods FMethod Abstraction FThe Math Class

3 2 Method Declaration ( ) { } public static int Max (int num1, int num2){ if (num1>num2) return num1; else return num2; } Method Body Modifier Return Type Method Name Formal Parameter List A method is a collection of statements that are grouped together to perform an operation. Method Header Method Body

4 3 Method body contains statements to implement the method. public int SumEven1To10() { int sum = 0; for (int i=2; i<=10; i=i+2) sum += i; MessageBox.Show("Sum of even numbers within"+ " 1 and 10 is" + sum); return sum; } public int SumEven1To10() { int sum = 0; for (int i=2; i<=10; i=i+2) sum += i; MessageBox.Show("Sum of even numbers within"+ " 1 and 10 is" + sum); return sum; } method body

5 4 Method Return Type Method return type specify the data type of the return value. The return type of a method can be any primitive data type (e.g. int, double ) or object reference (e.g. string ). The last statement executed in a method is the return statement. The data type of the return value must match the return type of the method. public int SumEven1To10(){ int sum = 0; for (int i=2; i<=10; i=i+2) sum += i; return sum; } public int SumEven1To10(){ int sum = 0; for (int i=2; i<=10; i=i+2) sum += i; return sum; } Return Type return sum; Return Statement The data type of sum matches the return type of the method

6 5 Method Without Return Value In case a method does not return any value to its caller, its return type should be void. public void PrintSumEven1To10(){ int sum = 0; for (int i=2; i<=10; i=i+2) sum += i; MessageBox.Show("sum of even numbers" + " within 1 to 10 =" + sum); } public void PrintSumEven1To10(){ int sum = 0; for (int i=2; i<=10; i=i+2) sum += i; MessageBox.Show("sum of even numbers" + " within 1 to 10 =" + sum); } Return Type No return value in the return statement. This return statement may be omitted! No return value in the return statement. This return statement may be omitted! return;

7 6 CAUTION – return in an if statement public int ThreeChoices(int n) { if (n > 0) return 1; else if (n == 0) return 0; else if (n < 0) return –1; } public int ThreeChoices(int n) { if (n > 0) return 1; else if (n == 0) return 0; else if (n < 0) return –1; } To fix this problem, delete if (n<0) in the code. if (n < 0) A return statement is required for a non-void method. The following method is logically correct, but it has a compilation error, because it is possible that this method does not return any value.

8 7 Execution of a Method public class SumEven(){ public SumEven(){ int sum sumEven1To10(); ("Sum of " + "even in 1 – 10 = " + sumEven; } public static void Main( ){ new SumEven(); } public class SumEven(){ public SumEven(){ int sum sumEven1To10(); ("Sum of " + "even in 1 – 10 = " + sumEven; } public static void Main( ){ new SumEven(); } sumEven1To10(); public int sumEven1To10(){ int sum = 0; for (int i=2; i<=10; i=i+2) sum += i; return sum; } public int sumEven1To10(){ int sum = 0; for (int i=2; i<=10; i=i+2) sum += i; return sum; } calling sumEven1To10. 1 3 MessageBox.Show Even= 2 SumEven called method sumEven1To10 The caller (i.e. the constructor of SumEven) invokes the called method (i.e. sumEven1To10 ) 1 called method sumEven1To10 Execute the statements in the body of the called method (i.e. sumEven1To10 ) 2 called method sumEven1To10 calling method SumEven return the required value from the called method (i.e. sumEven1To10 ) to the calling method (i.e. the constructor of SumEven) 3

9 8 Return Value of a Method public class SumEven(){ public SumEven(){ int sumEven= sumEven1To10(); Console.WriteLine("Sum of " + "even in 1 – 10 = " + sumEven; } public static void Main( ){ new SumEven(); } public class SumEven(){ public SumEven(){ int sumEven= sumEven1To10(); Console.WriteLine("Sum of " + "even in 1 – 10 = " + sumEven; } public static void Main( ){ new SumEven(); } public int sumEven1To10(){ int sum = 0; for (int i=2; i<=10; i=i+2) sum += i; return sum; } public int sumEven1To10(){ int sum = 0; for (int i=2; i<=10; i=i+2) sum += i; return sum; } The return value (i.e. 30) is then assigned to the variable sumEven. The statement int sumEven = sumEven1To10(); is executed in TWO steps: 1. Invoke the method sumEven1To10. 2. Assign the return value to variable sumEven. 30 sumEven1To10(); 30 int sumEven=

10 9 Memory Space Assigned to a Method -1 public class SumEven(){ public SumEven(){ int sumEven = SumEven1To10(); Console.WriteLine("Sum of " + "even in 1 – 10 = " + sumEven; } public static void Main( ){ new SumEven(); } public class SumEven(){ public SumEven(){ int sumEven = SumEven1To10(); Console.WriteLine("Sum of " + "even in 1 – 10 = " + sumEven; } public static void Main( ){ new SumEven(); } SumEven1To10(); public int sumEven1To10(){ int sum = 0; for (int i=2; i<=10; i=i+2) sum += i; return sum; } public int sumEven1To10(){ int sum = 0; for (int i=2; i<=10; i=i+2) sum += i; return sum; } calling sumEven1To10. 1 Memory space is assigned to the local variables of a method when it is activated(called). 0 0 Memory space is assigned to sumEven 1 Memory space is assigned to sum Memory(Stack): constructor SumEven sumEven undefined method SumEven1To10 sum 0

11 10 Memory Space Assigned to a Method -2 public class SumEven(){ public SumEven(){ int sum SumEven1To10();.WriteLine("Sum of " + "even in 1 – 10 = " + sumEven; } public static void Main( ){ new SumEven(); } public class SumEven(){ public SumEven(){ int sum SumEven1To10();.WriteLine("Sum of " + "even in 1 – 10 = " + sumEven; } public static void Main( ){ new SumEven(); } SumEven1To10(); public int SumEven1To10(){ int sum = 0; for (int i=2; i<=10; i=i+2) sum += i; return sum; } public int SumEven1To10(){ int sum = 0; for (int i=2; i<=10; i=i+2) sum += i; return sum; } Console Even= 2 2 sum becomes 30 after execution of the for statement. Memory(Stack): constructor SumEven sumEven undefined method SumEven1To10 sum 0 30

12 11 Memory Space Assigned to a Method -3 public class SumEven(){ public SumEven(){ int sum sumEven1To10();.WriteLine("Sum of " + "even in 1 – 10 = " + sumEven; } public static void Main( ){ new SumEven(); } public class SumEven(){ public SumEven(){ int sum sumEven1To10();.WriteLine("Sum of " + "even in 1 – 10 = " + sumEven; } public static void Main( ){ new SumEven(); } SumEven1To10(); public int SumEven1To10(){ int sum = 0; for (int i=2; i<=10; i=i+2) sum += i; return sum; } public int SumEven1To10(){ int sum = 0; for (int i=2; i<=10; i=i+2) sum += i; return sum; } 3 Console Even= 3 Return the value 30 to its caller ( SumEven ) Memory(Stack): constructor SumEven sumEven undefined method sumEven1To10 sum 0 30

13 12 Memory Space Assigned to a Method -4 public class SumEven(){ public SumEven(){ int sum sumEven1To10();.WriteLine("Sum of " + "even in 1 – 10 = " + sumEven; } public static void Main( ){ new SumEven(); } public class SumEven(){ public SumEven(){ int sum sumEven1To10();.WriteLine("Sum of " + "even in 1 – 10 = " + sumEven; } public static void Main( ){ new SumEven(); } SumEven1To10(); public int SumEven1To10(){ int sum = 0; for (int i=2; i<=10; i=i+2) sum += i; return sum; } public int SumEven1To10(){ int sum = 0; for (int i=2; i<=10; i=i+2) sum += i; return sum; } Console Even= 3 Return the value 30 to its caller ( SumEven ) Memory(Stack): constructor SumEven sumEven undefined method sumEven1To10 sum 0 30 3 The memory assigned to method sumEven1To10 is de-allocated (No longer exist)

14 13 Memory Space Assigned to a Method -5 public class SumEven(){ public SumEven(){ int sum sumEven1To10();.WriteLine("Sum of " + "even in 1 – 10 = " + sumEven; } public static void Main( ){ new SumEven(); } public class SumEven(){ public SumEven(){ int sum sumEven1To10();.WriteLine("Sum of " + "even in 1 – 10 = " + sumEven; } public static void Main( ){ new SumEven(); } SumEven1To10(); public int SumEven1To10(){ int sum = 0; for (int i=2; i<=10; i=i+2) sum += i; return sum; } public int SumEven1To10(){ int sum = 0; for (int i=2; i<=10; i=i+2) sum += i; return sum; } 3 Console Even= Memory(Stack): constructor SumEven sumEven undefined 30 3 Return the value 30 to its caller ( SumEven ) The memory assigned to method SumEven1To10 is de-allocated (No longer exist) The return value is assigned to SumEven. int sumEven=

15 14 Control Flow in Execution of C# Program -1 public class Sum{ public Sum(){ Console.WriteLine ("Sum of odd numbers in 1 - 10 = " + SumOdd()); Console.WriteLine ("Sum of even numbers in 1 - 10 = " + SumEven()); } public int SumOdd(){ int sum = 0; for (int i=1; i<10; i=i+2){ sum += i; } return sum; } public int SumEven(){ int sum = 0; for (int i=2; i<10; i=i+2){ sum += i; } return sum; } public static void Main( ){ new Sum(); } public class Sum{ public Sum(){ Console.WriteLine ("Sum of odd numbers in 1 - 10 = " + SumOdd()); Console.WriteLine ("Sum of even numbers in 1 - 10 = " + SumEven()); } public int SumOdd(){ int sum = 0; for (int i=1; i<10; i=i+2){ sum += i; } return sum; } public int SumEven(){ int sum = 0; for (int i=2; i<10; i=i+2){ sum += i; } return sum; } public static void Main( ){ new Sum(); } Memory(Stack): method Main 1 Execution starts from the Main method constructor Sum

16 15 Control Flow in Execution of C# Program -2 public class Sum{ public Sum(){ Console.WriteLine ("Sum of odd numbers in 1 - 10 = " + SumOdd()); Console.WriteLine ("Sum of even numbers in 1 - 10 = " + SumEven()); } public int SumOdd(){ int sum = 0; for (int i=1; i<10; i=i+2){ sum += i; } return sum; } public int SumEven(){ int sum = 0; for (int i=2; i<10; i=i+2){ sum += i; } return sum; } public static void Main( ){ new Sum(); } public class Sum{ public Sum(){ Console.WriteLine ("Sum of odd numbers in 1 - 10 = " + SumOdd()); Console.WriteLine ("Sum of even numbers in 1 - 10 = " + SumEven()); } public int SumOdd(){ int sum = 0; for (int i=1; i<10; i=i+2){ sum += i; } return sum; } public int SumEven(){ int sum = 0; for (int i=2; i<10; i=i+2){ sum += i; } return sum; } public static void Main( ){ new Sum(); } 1 2 3 Memory(Stack): method Main SumOdd sum 0 constructor Sum 25

17 16 public class Sum{ public Sum(){ Console.WriteLine("Sum of odd numbers in 1 - 10 = " + SumOdd()); Console.WriteLine("Sum of even numbers in 1 - 10 = " + SumEven()); } public int SumOdd(){ int sum = 0; for (int i=1; i<10; i=i+2){ sum += i; } return sum; } public int SumEven(){ int sum = 0; for (int i=2; i<10; i=i+2){ sum += i; } return sum; } public static void Main( ){ new Sum(); } public class Sum{ public Sum(){ Console.WriteLine("Sum of odd numbers in 1 - 10 = " + SumOdd()); Console.WriteLine("Sum of even numbers in 1 - 10 = " + SumEven()); } public int SumOdd(){ int sum = 0; for (int i=1; i<10; i=i+2){ sum += i; } return sum; } public int SumEven(){ int sum = 0; for (int i=2; i<10; i=i+2){ sum += i; } return sum; } public static void Main( ){ new Sum(); } Control Flow in Execution of C# Program -3 1 2 3 25 4 2525 Memory(Stack): Output: Sum of odd numbers in 1 – 10 = 25 Output: Sum of odd numbers in 1 – 10 = 25 method Main constructor Sum sumOdd sum 25

18 17 Control Flow in Execution of C# Program -4 public class Sum{ public Sum(){ Console.WriteLine ("Sum of odd numbers in 1 - 10 = " + SumOdd()); Console.WriteLine ("Sum of even numbers in 1 - 10 = " + SumEven()); } public int SumOdd(){ int sum = 0; for (int i=1; i<10; i=i+2){ sum += i; } return sum; } public int SumEven(){ int sum = 0; for (int i=2; i<10; i=i+2){ sum += i; } return sum; } public static void Main( ){ new Sum(); } public class Sum{ public Sum(){ Console.WriteLine ("Sum of odd numbers in 1 - 10 = " + SumOdd()); Console.WriteLine ("Sum of even numbers in 1 - 10 = " + SumEven()); } public int SumOdd(){ int sum = 0; for (int i=1; i<10; i=i+2){ sum += i; } return sum; } public int SumEven(){ int sum = 0; for (int i=2; i<10; i=i+2){ sum += i; } return sum; } public static void Main( ){ new Sum(); } 1 5 Memory(Stack): constructor Sum method Main Output: Sum of odd numbers in 1 – 10 = 25 Output: Sum of odd numbers in 1 – 10 = 25 6 SumEven sum 0 30

19 18 Control Flow in Execution of C# Program -5 public class Sum{ public Sum(){ Console.WriteLine ("Sum of odd numbers in 1 - 10 = " + SumOdd()); Console.WriteLine ("Sum of even numbers in 1 - 10 = " + SumEven()); } public int SumOdd(){ int sum = 0; for (int i=1; i<10; i=i+2){ sum += i; } return sum; } public int SumEven(){ int sum = 0; for (int i=2; i<10; i=i+2){ sum += i; } return sum; } public static void Main( ){ new Sum(); } public class Sum{ public Sum(){ Console.WriteLine ("Sum of odd numbers in 1 - 10 = " + SumOdd()); Console.WriteLine ("Sum of even numbers in 1 - 10 = " + SumEven()); } public int SumOdd(){ int sum = 0; for (int i=1; i<10; i=i+2){ sum += i; } return sum; } public int SumEven(){ int sum = 0; for (int i=2; i<10; i=i+2){ sum += i; } return sum; } public static void Main( ){ new Sum(); } 1 5 6 7 Output: Sum of odd numbers in 1 – 10 = 25 Output: Sum of odd numbers in 1 – 10 = 25 3030 Sum of even numbers in 1 – 10 = 30 Memory(Stack): constructor Sum method Main sumEven sum 30

20 19 Passing Parameters to a Method Parameters are used to pass data from the calling code to the called method. The data to be passed is given in the form of an actual argument. The method names this data as a formal parameter. public class Sum { public Sum(){ 100 int sum = Sum1ToN( 100 ); Console.WriteLine ("Sum 1-" +end + " = " + sum); } public int Sum1ToN(int n ){ int sum=0; for(int i=1; i<= n ; i++) sum += i; return sum; } public static void Main( ){ new Sum(); } public class Sum { public Sum(){ 100 int sum = Sum1ToN( 100 ); Console.WriteLine ("Sum 1-" +end + " = " + sum); } public int Sum1ToN(int n ){ int sum=0; for(int i=1; i<= n ; i++) sum += i; return sum; } public static void Main( ){ new Sum(); } formal parameter Calling method Called method actual parameter (argument) actual parameter (argument) calling code

21 20 public class Sum { public Sum(){ int sum = Sum1ToN( 100 ); Console.WriteLine (" 1-" +end + " = " + sum); } public int Sum1ToN(int n ){ int sum=0; for(int i=1; i<= n ; i++) sum += i; return sum; } public static void Main( ){ new Sum(); } public class Sum { public Sum(){ int sum = Sum1ToN( 100 ); Console.WriteLine (" 1-" +end + " = " + sum); } public int Sum1ToN(int n ){ int sum=0; for(int i=1; i<= n ; i++) sum += i; return sum; } public static void Main( ){ new Sum(); } The formal parameter is assigned the actual argument at call time The formal parameter behaves like a local variable of the method. Memory(Stack): constructor Sum sum n sum 0 1 2 100 Sum1ToN Sum 1-

22 21 Data Type and Value of Actual Parameters An actual parameter must carry a value. It can be a constant literal or an initialized variable. public class Sum { public Sum(){ string nString = txtN.Text; int n = int.Parse(nString); MessageBox.Show("Sum 1-" + n + " = " + Sum1ToN( n )); } public int Sum1ToN(int n ){ int sum=0; for(int i=1; i<= n ; i++) sum += i; return sum; } public static void Main( ){ new Sum();; } public class Sum { public Sum(){ string nString = txtN.Text; int n = int.Parse(nString); MessageBox.Show("Sum 1-" + n + " = " + Sum1ToN( n )); } public int Sum1ToN(int n ){ int sum=0; for(int i=1; i<= n ; i++) sum += i; return sum; } public static void Main( ){ new Sum();; } Memory(Stack): constructor Sum nString n txtN.Text; "10" Sum1ToN n sum 0 10 n = int.Parse(nString); Sum1ToN( n ) Assuming that txtN.Text is "10"

23 22 Value of Actual Parameter is Copied to the Corresponding Formal Parameter public class Sum { public Sum(){ String nString = txtN.Text; int n = int.Parse(nString); MessageBox.Show("Sum 1-" + n + " = " + Sum1ToN( n )); } public int Sum1ToN(int n ){ int sum=0; for(int i=1; i<= n ; i++) sum += i; return sum; } public static void Main( ){ new Sum(); } public class Sum { public Sum(){ String nString = txtN.Text; int n = int.Parse(nString); MessageBox.Show("Sum 1-" + n + " = " + Sum1ToN( n )); } public int Sum1ToN(int n ){ int sum=0; for(int i=1; i<= n ; i++) sum += i; return sum; } public static void Main( ){ new Sum(); } Memory(Stack): constructor Sum nString n "10" Sum1ToN n sum 0 10 They have their own memory locations although their names are the same. formal parameter in Sum1ToN local variable in Sum Assuming that txtN.Text is "10"

24 23 Formal Parameters and Actual Parameters NOT necessary to Have the Same Name -1 using System; public class Sum { public Sum() { int s = int.Parse(txtS.Text); int e = int.Parse(txtE.Text); Console.WriteLine("Sum of even in " + s " - " + e + " = " + SumEven ( s, e )); } public int SumEven(int start, int end) { int sum=0; if (start%2!=0) start++; for(int i=start; i<=end; i=i+2) sum += i; return sum; } public static void Main( ) { new Sum(); } using System; public class Sum { public Sum() { int s = int.Parse(txtS.Text); int e = int.Parse(txtE.Text); Console.WriteLine("Sum of even in " + s " - " + e + " = " + SumEven ( s, e )); } public int SumEven(int start, int end) { int sum=0; if (start%2!=0) start++; for(int i=start; i<=end; i=i+2) sum += i; return sum; } public static void Main( ) { new Sum(); } Memory(Stack): constructor Sum s e 10 1 SumEven start end sum 0 SumEven ( s, e ) 1 10

25 24 Formal Parameters and Actual Parameters NOT necessary to Have the Same Name - 2 public class Sum { public Sum() { int s = int.Parse(txtS.Text); int e = int.Parse(txtE.Text); Console.WriteLine("Sum of even in " + s " - " + e + " = " + sumEven ( s, e )); } public int sumEven(int start, int end) { int sum=0; if (start%2!=0) start++; for(int i=start; i<=end; i=i+2) sum += i; return sum; } public static void Main( ) { new Sum(); } public class Sum { public Sum() { int s = int.Parse(txtS.Text); int e = int.Parse(txtE.Text); Console.WriteLine("Sum of even in " + s " - " + e + " = " + sumEven ( s, e )); } public int sumEven(int start, int end) { int sum=0; if (start%2!=0) start++; for(int i=start; i<=end; i=i+2) sum += i; return sum; } public static void Main( ) { new Sum(); } Memory(Stack): constructor Sum s e 10 1 SumEven start end sum 0 1 10 if (start%2!=0) start++; 2 30 for(int i=start; i<=end; i=i+2) sum += i; 2

26 25 Formal Parameters and Actual Parameters NOT necessary to Have the Same Name -3 public class Sum { public Sum() { int s = int.Parse(txtS.Text); int e = int.Parse(txtE.Text); MessageBox.Show("Sum of even in " + s " - " + e + " = " + SumEven ( s, e )); } public int SumEven(int start, int end) { int sum=0; if (start%2!=0) start++; for(int i=start; i<=end; i=i+2) sum += i; return sum; } public static void Main( ) { new Sum(); } public class Sum { public Sum() { int s = int.Parse(txtS.Text); int e = int.Parse(txtE.Text); MessageBox.Show("Sum of even in " + s " - " + e + " = " + SumEven ( s, e )); } public int SumEven(int start, int end) { int sum=0; if (start%2!=0) start++; for(int i=start; i<=end; i=i+2) sum += i; return sum; } public static void Main( ) { new Sum(); } Memory(Stack): constructor Sum s e 10 1 SumEven start end sum 30 2 10 return sum; 30 Output: Sum of even numbers in 1 – 10 = 30 Output: Sum of even numbers in 1 – 10 = 30

27 26 using System.Windows.Forms; public class ManyHello { public ManyHello(){ int times = int.Parse(txtTimes.Text); string name = txtName.Text; SayHello( name, times )); } public void SayHello(String name, int count ){ for(int i=1; i<= count ; i++) MessageBox.Show("Hello, "+ name ); } public static void Main( ){ new ManyHello(); } Number of Formal Parameters and Actual Parameters MUST be the Same Actual parameters match the formal parameters from left to right.

28 27 using System.Windows.Forms; public class ManyHello { public ManyHello(){ int times = int.Parse(txtTimes.Text); string name = txtName.Text; SayHello( name, times )); } public void SayHello(string name, int count ){ for(int i=1; i<= count ; i++) MessageBox.Show("Hello, "+ name ); } public static void Main( ){ new ManyHello(); } Data Type of Formal Parameters and Actual Parameters MUST be Compatible same data type

29 28 Rules for Passing Parameters Actual parameters are also called arguments. Actual parameters are passed to a method using the pass-by- value scheme. Actual parameters are matched to the formal parameters from left to right. The data type of an argument must be assignment compatible to the data type of the matching formal parameter. The number of actual parameters in the method call must match the number of formal parameters in the method signature. Formal parameters and actual parameters do not have to have the same name. Local copies, which are distinct from actual parameters, are created even if the formal parameters and actual parameters share the same name. Formal parameters are input to a method, and they are local to the method. Changes made to the formal parameters will not affect the value of corresponding actual parameters.

30 29 Local Variables FA local variable is a variable that is declared within a method declaration. FMemory space for local variables are allocated only during the execution of the method. When the method execution completes, memory space will be de- allocated. FThe programmer must declare and then initialize a local variable. Otherwise, its value is undefined. FScope: the part of the program where the variable can be referenced. FThe scope of a local variable starts from its declaration and continues to the end of the block that contains the variable. A local variable must be declared before it can be used. FYou can declare a local variable with the same name multiple times in different non-nesting blocks in a method, but you cannot declare a local variable twice in nested blocks.

31 30 Scope of Local Variables -1 FLocal Variable: a variable defined inside a method. FScope: the part of the program where the variable can be referenced. FA local variable must be declared before it can be used. FThe scope of a local variable starts from its declaration and continues to the end of the block that contains the variable. public void LocalVarInBlock() { int sumOdd = 0; Console.Write("sum of "); for (int i=1; i<10; i=i+2) { Console.Write( i +" "); sumOdd += i; } Console.WriteLine(" = "+sumOdd); } public void LocalVarInBlock() { int sumOdd = 0; Console.Write("sum of "); for (int i=1; i<10; i=i+2) { Console.Write( i +" "); sumOdd += i; } Console.WriteLine(" = "+sumOdd); } scope of i scope of sumOdd

32 31 Local Variables can be Accessed Only Within the Block it is Declared public void LocalVarInBlock() { int sumOdd = 0; Console.Write ("sum of "); for (int i=1; i<10; i=i+2) { Console.Write( i +" "); sumOdd += i; } Console.WriteLine(" = "+sumOdd); } public void LocalVarInBlock() { int sumOdd = 0; Console.Write ("sum of "); for (int i=1; i<10; i=i+2) { Console.Write( i +" "); sumOdd += i; } Console.WriteLine(" = "+sumOdd); } Console.WriteLine("i = "+ i); Compilation Error: Cannot find Symbol: variable i Compilation Error: Cannot find Symbol: variable i X X

33 32 Scope of a local variable - 1 public void LocalVarOfSameName(){ int sumOdd = 0; int i = 2; for (int i = 1; i<10; i = i+2){ sumOdd += i; } Console.WriteLine("Sum of Odds(1-10)=" + sumOdd); Console.WriteLine("i = " + i ); } public void LocalVarOfSameName(){ int sumOdd = 0; int i = 2; for (int i = 1; i<10; i = i+2){ sumOdd += i; } Console.WriteLine("Sum of Odds(1-10)=" + sumOdd); Console.WriteLine("i = " + i ); } Memory(Stack): LocalVarOfSameName i sumOdd 0 2

34 33 Scope of a local variable - 2 public void LocalVarOfSameName(){ int sumOdd = 0; int i = 2; for (int i = 1; i<10; i = i+2){ sumOdd += i; } Console.WriteLine("Sum of Odds(1-10)=" + sumOdd); Console.WriteLine("i = " + i ); } public void LocalVarOfSameName(){ int sumOdd = 0; int i = 2; for (int i = 1; i<10; i = i+2){ sumOdd += i; } Console.WriteLine("Sum of Odds(1-10)=" + sumOdd); Console.WriteLine("i = " + i ); } Memory(Stack): LocalVarOfSameName i sumOdd 0 2 1 i for (int i = 1; i<10; i = i+2){ sumOdd += i; } 25 9

35 34 Memory(Stack): 11 i LocalVarOfSameName i sumOdd 25 2 Scope of a local variable - 3 public void LocalVarOfSameName(){ int sumOdd = 0; int i = 2; for (int i = 1; i<10; i = i+2){ sumOdd += i; } Console.WriteLine("Sum of Odds(1-10)=" + sumOdd); Console.WriteLine("i = "+ i ); } public void LocalVarOfSameName(){ int sumOdd = 0; int i = 2; for (int i = 1; i<10; i = i+2){ sumOdd += i; } Console.WriteLine("Sum of Odds(1-10)=" + sumOdd); Console.WriteLine("i = "+ i ); } Console.WriteLine("Sum of Odds(1-10)=" + sumOdd); Output: Sum of Odds (1-10) = 25 Output: Sum of Odds (1-10) = 25 i for for The variable i declared in the for loop is not accessible anymore after execution of the for loop!

36 35 Local Variables with Same Name - 4 public void LocalVarOfSameName(){ int sumOdd = 0; int i = 2; for (int i = 1; i<10; i = i+2){ sumOdd += i; } Console.WriteLine("Sum of Odds(1-10)=" + sumOdd); Console.WriteLine("i = "+ i ); } public void LocalVarOfSameName(){ int sumOdd = 0; int i = 2; for (int i = 1; i<10; i = i+2){ sumOdd += i; } Console.WriteLine("Sum of Odds(1-10)=" + sumOdd); Console.WriteLine("i = "+ i ); } Memory(Stack): Console.WriteLine("i = "+ i ); Output: Sum of Odds (1-10) = 25 Output: Sum of Odds (1-10) = 25 i = 2 LocalVarOfSameName i sumOdd 25 2

37 36 Each Local Variable Must Have a Unique Name // print number series from 1 to 8 in the form of a rectangle. for (int row=1; row<=limit; row++){ colcolcol for (int col=1; col<=limit; col++) col if (row>=col) col Console.Write(col); else Console.Write("*"); Console.WriteLine(); } // print number series from 1 to 8 in the form of a rectangle. for (int row=1; row<=limit; row++){ colcolcol for (int col=1; col<=limit; col++) col if (row>=col) col Console.Write(col); else Console.Write("*"); Console.WriteLine(); } 1******* 12****** 123***** 1234**** 12345*** 123456** 1234567* 12345678 1******* 12****** 123***** 1234**** 12345*** 123456** 1234567* 12345678 for (int i =1; i <=limit; i ++){ jjj for (int j =1; j <=limit; j ++) j if ( i >= j ) j Console.Write( j ); else Console.Write("*"); Console.WriteLine(); } for (int i =1; i <=limit; i ++){ jjj for (int j =1; j <=limit; j ++) j if ( i >= j ) j Console.Write( j ); else Console.Write("*"); Console.WriteLine(); } for (int i =1; i <=limit; i ++){ iii for (int i =1; i <=limit; i ++) i if ( i >= i ) i Console.Write( i ); else Console.Write("*"); Console.WriteLine(); } for (int i =1; i <=limit; i ++){ iii for (int i =1; i <=limit; i ++) i if ( i >= i ) i Console.Write( i ); else Console.Write("*"); Console.WriteLine(); } X X    

38 37 Methods in Math Class All the methods and constants in the class Math are class (static) members. Use the syntax. to access a class constant in another class. e.g. Math.PI Use the syntax. ( ) to access a class method in another class. e.g. Math.Max( a, b ) public class FindBiggest { public FindBiggest() { int a = int.Parse(txtA.Text); int b = int.Parse(txtB.Text); int c = int.Parse(txtC.Text); int big = Math.Max(a,b) ; big = Math.Max(big,c) ; MessageBox.Show("The biggest value is"+big); } public static void Main( ) { new FindBiggest(); }

39 38 Formal Parameter & Actual Parameter public double LongestLine(){ int x1, y1, x2, y2, x3, y3; //Ask the user to enter the values of x1, y1,...... double line1 = LineLength(x1, y1, x2, y2); double line2 = LineLength(x1, y1, x3, y3); double line3 = LineLength(x3, y3, x2, y2); double maxOfLine1AndLine2 = Math.Max(line1, line2); return Math.Max(maxOfLine1AndLine2, line3); } public double LineLength(int xP, int yP, int xQ, int yQ){ return Math.Sqrt(Math.Pow(xP-xQ, 2) + Math.Pow(yP-yQ, 2)); } actual parameter (argument) actual parameter (argument) formal parameter Number of actual parameters must match number of formal parameter.

40 39 Graphical Illustration of Parameter Passing :LongestLine x1 y1 x2 y2 x3 y3 :LongestLine x1 y1 x2 y2 x3 y3 1 2 0 3 4 6 Memory space allocated to method LineLength: xP yP xQ yQ double line1 = LineLength(x1, y1, x2, y2); 1 2 0 3

41 40 Graphical Illustration of Parameter Passing -2 :LongestLine x1 y1 x2 y2 x3 y3 :LongestLine x1 y1 x2 y2 x3 y3 1 2 0 3 4 6 Memory space allocated to method LineLength: xP yP xQ yQ double line2 = LineLength(x3, y3, x2, y2); 4 6 0 3

42 41 Names of Formal Parameter // This class shows how to pass parameter from one method to another public class PointsAndLines{ public double LongestLine(){ int x1, y1, x2, y2, x3, y3; //Ask the user to enter the values of x1, y1, …, y3... double line1 = LineLength(x1, y1, x2, y2); double line2 = LineLength(x1, y1, x3, y3); double line3 = LineLength(x3, y3, x2, y2); double maxOfLine1AndLine2 = Math.Max(line1, line2); return Math.Max(maxOfLine1AndLine2, line3); } public double LineLength(int x1, int y1, int x2, int y2 ){ return Math.Sqrt( Math.Pow(x1-x2, 2) + Math.Pow(y1-y2, 2) ); } public static void Main( ){ PointsAndLines obj = new PointsAndLines(); double maxLine = obj.LongestLine(); } Naming of formal parameter does not affect the result of the execution of the program

43 42 Graphical Illustration of Parameter Passing -3 :LongestLine x1 y1 x2 y2 x3 y3 :LongestLine x1 y1 x2 y2 x3 y3 1 2 0 3 4 6 Memory space allocated to method LineLength: x1 y1 x2 y2 double line2 = LineLength(x2, y2, x1, y1); 0 3 1 2

44 43 Data Type of Actual Parameter & its Corresponding Formal Parameter -1 public class Person { public Person(string name, char sex, int age){... }... } public class Person { public Person(string name, char sex, int age){... }... } Data type of an actual parameter and its corresponding formal parameter must be the same!  XX Person tim = new Person( "Tim", 'M', 10.5 ); XX Must be the same data type! Person lily = new Person( "Lily", 'F', 10 ); Person sam = new Person( "Sam", "F", 10 );

45 44 Data Type of Actual Parameter & its Corresponding Formal Parameter -2 public class Person { public Person(string name, char sex, float age){... }... } public class Person { public Person(string name, char sex, float age){... }... } Data type of an actual parameter and its corresponding formal parameter must be the same! Person lily = new Person( "Lily", 'F', 10 );  Person sam = new Person( "Sam", 'M', 10.5F ); Person tim = new Person( "Tim", 'M', 10.5 ); XX 

46 45 Result of One Method is Passed As Actual Parameter to Another Method -1 public class PointsAndLines { public double LongestLine(){ int x1, y1, x2, y2, x3, y3; //Ask the user to enter the values of x1, y1, …, y3... double line1 = LineLength(x1, y1, x2, y2); double line2 = LineLength(x1, y1, x3, y3); double line3 = LineLength(x3, y3, x2, y2); double maxOfLine1AndLine2 = Math.Max(line1, line2); return Math.Max( maxOfLine1AndLine2, line3 ); } public double LineLength(int x1, int y1, int x2, int y2){ return Math.Sqrt( Math.Pow(x1-x2,2) + Math.Pow(y1-y2,2) ); } public static void Main( ){ PointsAndLines obj = new PointsAndLines(); double maxLine = obj.LongestLine(); } slice 41 // return Math.Max( Math.Max(line1, line2), line3 ); Math.Pow(x1-x2,2)Math.Pow(y1-y2,2)

47 46 Result of One Method is Passed As Actual Parameter to Another Method -2 public class PointsAndLines { public double LongestLine(){ int x1, y1, x2, y2, x3, y3; //Ask the user to enter the values of x1, y1, …, y3... return Math.Max( Math.Max(LineLength(x1,y1,x2,y2), LineLength(x1,y1,x3,y3)), LineLength(x3,y3,x2,y2) ); } public double LineLength(int x1, int y1, int x2, int y2){ return Math.Sqrt( Math.Pow(x1-x2, 2) + Math.Pow(y1-y2, 2) ); } public static void Main( ){ PointsAndLines obj = new PointsAndLines(); double maxLine = obj.LongestLine(); }

48 47 Method Abstraction Method Signature includes – the name of the method & – the parameter list of the method Methods with different signatures (including same name but different parameter lists) are different methods. FYou can think of the method body as a black box that contains the detailed implementation for the method. This is known as information hiding. FDuring development of large program, 'divide and conquer' approach should be used to divide the large problem into sub-problems.

49 48 Method Overloading In a class, methods having the same name but different parameter lists are overloaded methods. e.g. public static int Max(int num1, int num2); public static double Max(double num1, double num2); public static int Max(int num1, int num2, int num3); overloaded methods overloaded methods Different Method Signatures

50 49 Example: Overloaded Methods public class OverloadedMethods{ public OverloadedMethods() { Console.WriteLine("DailyRate: " + ComputePay (10, 150)); Console.WriteLine("Salary: " + ComputePay (25000)); Console.WriteLine("Commission: " + ComputePay (500, 100, 30)); } //compute pay for temporary employee public double ComputePay (int daysWorked, double dailyRate){ return daysWorked*dailyRate; } //compute pay for permanent employee public double ComputePay (double annual){ return annual/12; } //compute pay for commision-based employee public double ComputePay (double basic, double rate, int numJobs){ return basic + rate*numJobs; } public static void Main( ){ new OverloadedMethods(); Console.ReadLine(); } public class OverloadedMethods{ public OverloadedMethods() { Console.WriteLine("DailyRate: " + ComputePay (10, 150)); Console.WriteLine("Salary: " + ComputePay (25000)); Console.WriteLine("Commission: " + ComputePay (500, 100, 30)); } //compute pay for temporary employee public double ComputePay (int daysWorked, double dailyRate){ return daysWorked*dailyRate; } //compute pay for permanent employee public double ComputePay (double annual){ return annual/12; } //compute pay for commision-based employee public double ComputePay (double basic, double rate, int numJobs){ return basic + rate*numJobs; } public static void Main( ){ new OverloadedMethods(); Console.ReadLine(); } Output: DailyRate: 1500.0 Salary: 2083.3333333333335 Commission: 3500.0Output: DailyRate: 1500.0 Salary: 2083.3333333333335 Commission: 3500.0

51 Passing parameters to overloaded methods public class Maximum { public double Max(double a, double b){ if (a>b) return a; else return b; } public double Max(double a, dobule b, double c){ return Max( Max(a,b), c ); } public double Max(double a, dobule b, double c, double d){ return Max( Max(a,b), Max(c,d) ); } public int Max(int a, int b, int c){ return (int)(Max( Max(a,b), c )); } public class Maximum { public double Max(double a, double b){ if (a>b) return a; else return b; } public double Max(double a, dobule b, double c){ return Max( Max(a,b), c ); } public double Max(double a, dobule b, double c, double d){ return Max( Max(a,b), Max(c,d) ); } public int Max(int a, int b, int c){ return (int)(Max( Max(a,b), c )); } double a, b, c, d; int i, j, m, n; double a, b, c, d; int i, j, m, n; d = Max(a,b); d = Max(a,b,c); d = Max(a,b,c,d); d = Max(i,j,m,n); i = Max(m,n,j); i = Max(m,n); X

52 51 Ambiguous Invocation Sometimes there may be two or more possible matches for an invocation of a method, but the compiler cannot determine the most specific match. This is referred to as ambiguous invocation. Ambiguous invocation is a compilation error. public class AmbiguousOverloading {... public void ShowError() { Console.WriteLine( Max(1,2) ); } public double Max(int num1, double num2) { if (num1 > num2) return num1; else return num2; } public double Max(double num1, int num2) { if (num1 > num2) return num1; else return num2; }... } public class AmbiguousOverloading {... public void ShowError() { Console.WriteLine( Max(1,2) ); } public double Max(int num1, double num2) { if (num1 > num2) return num1; else return num2; } public double Max(double num1, int num2) { if (num1 > num2) return num1; else return num2; }... } This statement causes compilation error It is better to write only one method Max in this case: double public double Max(double num1, double double num2){ if (num1 > num2) return num1; else return num2; } It is better to write only one method Max in this case: double public double Max(double num1, double double num2){ if (num1 > num2) return num1; else return num2; }

53 52 Caution: Parameters are Passed by Values State of Memory public static void Swap( int a, int b ) { int temp; temp = a; a = b; b = temp; } A A A. A. parameters do not exist before the method execution At before swap A A Code x = 10; y = 20; Swap( x, y ); xx 10 y 20 The actual parameter remains unchanged when the corresponding formal parameter changes.

54 53 Pass-By-Value Scheme - 2 State of Memory public static void Swap(int a, int b) { int temp; temp = a; a = b; b = temp; } B B B. B. The values of the Actual Parameters are copied to the corresponding parameters. After is executed B B Code x = 10; y = 20; Swap( x, y ); xx 10 y 20 a 10 b 20 temp 10 actual parameters

55 54 Pass-By-Value Scheme - 3 State of Memory public static void Swap(int a, int b) { int temp; temp = a; a = b; b = temp; } C C C. C. The values of the parameters are changed After is executed C C Code x = 10; y = 20; Swap( x, y ); xx 10 y 20 a 10 b 20 temp 10 20

56 55 Pass-By-Value Scheme - 4 State of Memory public static void Swap(int a, int b) { int temp; temp = a; a = b; b = temp; } D D D. D. Memory space is deallocated upon exiting the swap method. The actual parameters remain unchanged. At after swap D D Code x = 10; y = 20; Swap( x, y ); xx 10 y 20

57 56 Caution: Local Variables Must be Initialized public int Sum1To10( ){ int sum ; for ( int i=1; i<=10; i++) sum += i; return sum; } public int Sum1To10( ){ int sum ; for ( int i=1; i<=10; i++) sum += i; return sum; } sum must be initialized to zero! Without initializing local variables will cause compilation errors! sum must be initialized to zero! Without initializing local variables will cause compilation errors! int sum = 0; The End


Download ppt "1 Chapter 5: Methods FIntroducing Methods FDeclaring Methods FCalling Methods FLocal Variables in Methods FPass by Value FOverloading Methods FMethod."

Similar presentations


Ads by Google