1 / 86

Method and Scope of variable

Method and Scope of variable. 01204111 Computer and Programming. Outline. Introduction to Method Method declaration and Calling Scope of variable. Introduction to Method.

tyrone
Télécharger la présentation

Method and Scope of variable

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Method and Scope of variable 01204111 Computer and Programming

  2. Outline • Introduction to Method • Method declaration and Calling • Scope of variable

  3. Introduction to Method Method is one of the components of Class. Method is used to define a calculation mean (algorithm) to find some results. Even though this calculation pattern may be requested several time in the program body, it needs not to be rewritten. Instead , a method should be created to collect all statements of this calculation pattern together. The method must be named for being called (referenced) by any other method. The calling method (caller) must pass some variables (parameter or argument) needed in the calculation process of the called method. A method can be called several time in the program according to the necessity to solve the specific problem.

  4. Types of a method) • A method can bedivided into 2 following types : • Value returning Method • Non-Value returning Method (or Void Method) Until now, students have been experienced to write several statements in a single method which is Main(). In fact, besides the method Main, there may be any other methods within a class according to the necessity of a specific problem solving.

  5. Concept of writing a method Example : Writing a program that accepts an integer n from a user and print a rectangle of size n columns x n lines with a character ‘*’. Enter N: 3 ****** *** Enter N: 4 ******** **** **** Enter N: 6 ************ ****** ****** ****** ******

  6. Step Planning • Read integer to n, for example 4 is read to n. • Draw a rectangle using the following steps: • Advance to line1 • Print a line of 4 *’s. • Advance to line2 • Print a line of 4 *’s. • Advance to line3 • Print a line of 4 *’s. • Advance to line4 • Print a line of 4 *’s. ******** **** ****

  7. Programming Overview Program to print a rectangle Read the value of N Print a rectangle of size N x N Print N *’s on each line

  8. Writing the method Main โปรแกรมพิมพ์สี่เหลี่ยม • Now, we assume that the method PrintSquare exists. (In fact, it has not been defined yet) รับค่า N พิมพ์สี่เหลี่ยม ขนาด N x N static void Main() { int n = int.Parse(Console.ReadLine()); PrintSquare(n); Console.ReadLine(); } This statement has not been defined yet.

  9. เมธอดแสดงสี่เหลี่ยม • The method PrintSquarehas calledthe methodPrintLineforN times. Each time the method PrintLine is called, it prints a line with the length of N stars. static void PrintSquare(int n) { int i = 0; while(i < n) { PrintLine(n); i++; } } Print a rectangle of size N x N Print each line with the length of N stars This statement has not been defined yet.

  10. The method PrintLine • Once the method PrintLine is called (by the method PrintSquare), it prints a line with the length of N stars. If it is called for N times, it will print N lines (each line with the length of N stars. static void PrintLine(int n) { int i = 0; while(i < n) { Console.Write("*"); i++; } Console.WriteLine(); }

  11. Complete program using System;namespace box1{  class Program  {    static void PrintLine(int n)    {int i = 0;while(i < n)      {Console.Write("*");        i++;      }Console.WriteLine();    }     static void PrintSquare(int n)    {int i = 0;while(i < n)      {PrintLine(n);        i++;      }    } public static void Main(string[] args) {int n = int.Parse(Console.ReadLine());PrintSquare(n);Console.ReadLine();    }  }} is a called method (It is called by PrintSquare) is a called method (because it was called by Main). Also it is calling method (because it calls the method PrintLine). MethodPrintLine MethodPrintSquare MethodMain is a calling method (It call the method PrintSquare)

  12. Method Declaration and Example • The previous example is to provide students an understanding of a concept and idea of dividing a whole program into several smaller parts called method. As seen in the previous example, there are 3 non-value returning methods (or void methods) which are Main(), PrintSquare() and PrintLine().

  13. Declaration of Value Returning Method According to the slidenumber 4, a method can bedivided into 2 following types : Value Returning Method and Non-Value returning Method (or Void Method).This chapter will present how to declare and define Value returning Method. Syntax of Value-Returning Method Declaration static data type Method name( a parameter list ) { // Program Body (instruction part) of method } The declaration of Non-Value returning Method will be presented in the next chapter.

  14. Value-Returning Method Declaration The following example is the declaration of a method Poly to compute Polynomial of degree two ax2 + bx + c static double Poly(double a, double b, double c, double x) { return a*x*x + b*x + c; } Parameter list : a, b, c, x Data type of a result produced by Poly Method name :Poly

  15. Location of Method Declaration using System;namespace met_examples {  class Program  {    static doublePoly(double a, double b, double c, double x) {     return a*x*x + b*x + c;  } public static void Main()    { double a, b, result; int y; …………………………………………………………..; result = Poly(a, b, 8.25*3, math.sqrt(y)); ……………………..;    }  }} • A method is declared within a class. • A method can not declared within any other method.

  16. Component of Method Declaration • Method Declaration consists of 2 important parts: 1. Method heading static double Poly(double a, double b, double c, double x) { return a*x*x + b*x + c; } 2. Method body (collection of instructions of a method)

  17. ส่วนหัวของเมธอด (method header) static double Poly(double a, double b, double c, double x) • To declare to public and specify how to utilize this method, what this method compute , and what parameters this method request as the following sample: The objective of method header : The method Poly(double a, double b, double c, double x) compute the Polynomial of degree two ax2 + bx + c.

  18. ส่วนตัวของเมธอด (method body) The method body is a collection of instructions defined to compute something as stated on the heading. Other methods The methodPoly Collection of instructions which was executed to produce a value. Calling to the method Poly to calculate a value which was returned to a caller

  19. การนำเมธอดไปใช้ • A method can call any other methods defined in the class. The following example shows how the method Main() call the method Poly. public static void Main(string[] args)    { double k = 3;double y = Poly(1,2,4,k);Console.WriteLine(y);Console.ReadLine();    } Therefore, we call the method Main “Calling method” and call the method Poly “Called method” because it is called by Main.

  20. Example of calling a method (1) The program consists of 2 methods: Main and Poly. using System;namespacemet_examples{  class Program  {    static doublePoly(double a, double b, double c,double x)    {     return a*x*x + b*x + c;    }public static void Main()    { double k = 3; double y = Poly(1,2,4,k);Console.WriteLine(y);Console.ReadLine();    }  }} Main calls the method Poly. Program starts its execution at Main.

  21. Example of calling a method (2) using System;namespacemet_examples{  class Program  {    static doublePoly(double a, double b, double c,double x)    {     return a*x*x + b*x + c;    }public static void Main()    { double k = 3; double y = Poly(1,2,4,k);Console.WriteLine(y);Console.ReadLine();    }  }} Main sent its actual parameters (1,2,4,k) to formal parameters of Poly (a,b,c,x). 19 a 1 b 2 k 3 c 4 y 19 x 3 Output 19

  22. Parameter passing(1) using System;namespacemet_examples{  class Program  {    static doublePoly(double a, double b, double c,double x)    {     return a*x*x + b*x + c;    }public static void Main()    { double k = 3; double y = Poly(1,2,4,k);Console.WriteLine(y);Console.ReadLine();    }  }} The important step of calling a method is parameter passing to pass (send) parameter (s) from calling to called method.

  23. การส่งพารามิเตอร์ (2)    static doublePoly(double a, double b, double c,double x)    { ………………………………..; } public static void Main() { …………………………………..;     double y = Poly(1,2,4,k); …………………………………….; } • Parameter list of calling program (or caller) is Actual Parameter. Parameter list declared at the method heading is Formal Parameter. Therefore, the parameters of Main (1,2,4,k) is Actual Parameter and the parameters of Poly (a,b,c,x) are Formal Parameter. • Actual Parameters must be “matched” with Formal Parameterrespectively.Therefore the number of Actual Parameters andFormal Parameters must be equaland the data type of each pair must be compatible.

  24. การส่งพารามิเตอร์ (3) Formal Parameter    static doublePoly(double a, double b, double c,double x)    { ………………………………..; } public static void Main() { ………………………………;     double y = Poly(1,2,4,k); ………………………………; } Important remarks: • The number of Actual parameters and Formal parameters must be equal. • Actual parameter can bevariable, or constant, or expression while Formal parametermust only be a variable whose data type is compatible with Actual parameter. Actual Parameter

  25. Formal Parameter Parameter passing(4) static doublePoly(double a, double b, double c, double x) {     return a*x*x + b*x + c;  } public static void Main()    { double a, b, result; int y; …………………………………………………………..; result = Poly(a, 15.78, 8.25*3/2, math.sqrt(y)); ……………………..;    } Actual Parameter Parameter passing of the 1st pair is a sending-accepting variable to variable. Parameter passing of the 2nd pair is a sending-accepting constant to variable. Parameter passing of the 3rd pair is a sending-accepting an expression(8.25*3/2) to variable. Parameter passing of the 4th pair is a sending-accepting a function expression(math.sqrt) to variable.

  26. Parameter passing (5) Besides the same number, data type of Actual and Formal parameter must be compatible as shown in the following table :

  27. No matter how many Actual parametersare passed to Formal parameters, a called method always produces only 1 value which is returned to calling method. Called method Calling method a a 15.78 b Execution statements 1 output value c 8.25*3/2 Math.sqrt(y) x The output value is sent back to calling method by the statement “return”.

  28. Calling a method: Example 1 using System;namespacemet_examples{  class Program  {    static doublePoly(double a, double b, double c,double x)    {     return a*x*x + b*x + c;    }public static void Main()    { double k = 3;       double y = Poly(2,k,k+3,2);Console.WriteLine(y);Console.ReadLine();    }  }} 2 3 6 2 What is the output of this program ? 20

  29. Calling a method: Example 2 using System;namespacemet_examples{  class Program  {    static doublePoly(double a, double b, double c,double x)    { /* ละไว้ */}    public static void Main()    { double k = 3;       double y = Poly(2,k,k+3,2);Console.WriteLine(y);      y = Poly(1,1,1,10);Console.WriteLine(y);Console.WriteLine(Poly(1,2,3,2));Console.ReadLine();    }  }} What is the output of this program ? 20111 11

  30. คำสั่ง return (1) static int Min(int x, int y) { if(x < y) return x; return y; } The return statement send the output of the method Min back to a calling spot in the calling method. 15 x 100 static void Main(string [] args) { int a = int.Parse( Console.ReadLine()); int b = int.Parse( Console.ReadLine()); Console.WriteLine(Min(a,b)); } y 15 Calling spot : a = 100 b = 15 This example finds the smaller value between 2 integer numbers : a = 100 and b = 15. At the method Min, If x == 100 and y ==15, then y is returned to the statement Console.WriteLine (Min (a,b)); at the method Main.

  31. คำสั่ง return (2) static int Min(int x, int y) { if(x < y) return x; return y; } The return statement send the output of the method Min back to a calling spot in the calling method. 10 static void Main(string [] args) { int a = int.Parse( Console.ReadLine()); int b = int.Parse( Console.ReadLine()); Console.WriteLine(Min(a,b)); } x 10 y 100 Calling spot : a = 10 b = 100 This example finds the smaller value between 2 integer numbers : a = 10 and b = 100. At the method Min, If x == 10 and y ==100, then x is returned to the statement Console.WriteLine (Min (a,b)); at the method Main.

  32. Example program of Value-Returning Method (1) Example 1The following program calculate the number of ways of r-combinations of a set of n distinct objects : C(n, r) = n!/r! * (n – r)!(The program body is on the next slide.) • The MethodMain() : • Readn andr:nคือ the number of distinct objects andris the number of selected • objects. • Call the methodcombinationand pass n and r to it. • The Methodcombination() : • formal parametersof thecombination() acceptn andr from the method Main(). • Call the method fac()3 times :fac(n), fac(r),andfac(n-r) • to calculate n!, r!, and n-r! • return the calculation result ofn!/r!*(n – r)! to Main() • The Methodfac() : • formal parameterof the methodfac()accepts n from the combination(). • Calculate fac(n) and returnresult to the method the combination(). • Calculate fac(r) and return result to the method the combination(). • Calculate fac(n-r) andreturn result to the method the combination().

  33. static long fac(int n) { long factor; int x; if (n == 0) return 1; else { factor = n; x = n-1; while (x>=1){ factor = factor * x; x--; } return factor; } } static long combination(int n, int r) { return fac(n)/(fac(r)*fac(n-r)); } public static void Main(string[] args) { long nummeth; int n,r; Console.WriteLine("Enter the total of n"); n = int.Parse(Console.ReadLine()); Console.WriteLine("Enter the number selected"); r = int.Parse(Console.ReadLine()); nummeth = combination(n,r); Console.WriteLine(nummeth); Console.ReadLine(); }

  34. Example program of Value-Returning Method (2) Eample 2 The following program is to find Greatest Common Divisor (GCD) of 2 integer numbers. (The program example is on thenext slide) This program divided its execution into 2 methods which are Main and GreatestCommon. The method Main passes (sends) 2 Actual parameters to the method GreatestCommon to calculate the GCD) of these 2 integer numbers and return the result to Main. Remember : The Value-Returning Method returns only 1 output value to calling program.

  35. staticint greatestCommon(int a, int b) { int temp; if (a<b){ temp = a; a = b; b = temp; } if (a%b == 0) //ถ้า a mod b ลงตัว เมธอดนี้จะ return ค่า b ให้กับMain() return b; else { do { temp = a; a = b; b = temp%b; }while((a%b) != 0); return b; } } // end greatestCommon static void Main(string[] args){ int a, b; Console.Write("Enter the first integer numbers : "); a = int.Parse(Console.ReadLine()); Console.Write("Enter the second integer numbers : "); b = int.Parse(Console.ReadLine()); Console.WriteLine("GCD of {0} and {1} = {2}, a,b,greatestCommon(a,b)); }// end Main() Formal Parameters ActualParameters

  36. Example 3 : Example program of Value-Returning Method (3) The advantage of dividing a program into methods is to minimize a repetitiveness of program coding as the following example: There are 2 types of mobile promotion : • TypeA: Monthly payment 50 Baht,Free call50 minutes and 1.5 Baht per minute for the next minutes. • Type B: Monthly payment 150 Baht,Free call100 minutes and 1 Baht per minute for the next minutes. Write a program to read expected time taken, calculate a fee per month and suggest the better promotion.

  37. public static void Main(string[] args)    {Console.Write("Enter expected usage: ");int u = int.Parse(Console.ReadLine());double price1;if(u <= 50)        price1 = 50;else        price1 = 50 + (u - 50)*1.5;double price2;if(u <= 100)        price2 = 150;else        price2 = 150 + (u - 100)*1.0;if(price1 < price2)Console.WriteLine("Plan A is better.");elseConsole.WriteLine("Plan B is better.");Console.ReadLine();    } Write a whole program within a single method. • Consider 2 parts of the program that calculate fee according to type A and Type B promotions . • We found that, even though the figures and variables are different, the fee calculation patterns are the same.

  38. The same calculation patterns of both promotion types • The fee calculation patterns of both promotion types which are the same, can be rewritten as a method with a parameter list that accepts a set of different figures. double price1;if(u <= 50)      price1 = 50;else      price1 = 50 + (u - 50)*1.5; double price2;if(u <= 100)      price2 = 150;else      price2 = 150 + (u -100)*1.0; ราคาต่อนาทีในส่วนที่เหลือ จำนวนนาทีที่โทรฟรี ค่าใช้จ่ายรายเดือน

  39. A method for a fee calculation     static doubleCalculatePrice(doublemonthlyFee,doublefreeMinutes,double rate,double usage)    {if(usage <= freeMinutes)        return monthlyFee;else        return monthlyFee + (usage - freeMinutes) * rate;    } • The calculation parts of this program are collected within a method named CalculatePrice with its parameter list : monthlyFee, freeMinutes, rate and usage to which the calling method can send any other sets of different values.

  40. The Main method of a fee calculation program public static void Main(string[] args)    {Console.Write("Enter expected usage: ");int u = int.Parse(Console.ReadLine());double price1 = CalculatePrice(50, 50, 1.5, u);double price2 = CalculatePrice(150, 100, 1.0, u);if(price1 < price2)Console.WriteLine("Plan A is better.");elseConsole.WriteLine("Plan B is better.");Console.ReadLine();    } • This program is shorter and more readible.

  41. Example program of Value-Returning Method (4) In some cases, there may not be a parameter passing between Actual and Formal parameter because the program is designed so that the called method can read inputs of its own. Example4 : In this program, the methods Deposit() and Withdraw() have noFormal Parameters because they are called by the method Main without passing any actual parameters. Instead, both Deposit and Withdraw read their input values within methods themselves.

  42. static int Deposit() { int s; Console.Write("Amount to deposit : "); s = int.Parse(Console.ReadLine()); return s; } // end Deposit static int Withdraw(){ int s; Console.Write("Amount to withdraw : "); s = int.Parse(Console.ReadLine()); return s; } // end Withdraw static void Balance (int bal){ Console.WriteLine ("Balance is : {0}",bal); } // end Balance static void Main(string[] args){ int b, bal = 0; bal = bal + Deposit(); // เรียกใช้ Method Deposit b = Withdraw(); // เรียกใช้ Method Withdraw while (b > bal){ Console.WriteLine("Money is not enought!!!"); Balance(bal); // เรียกใช้ Procedure Balancre b = Withdraw(); } bal = bal - b; Balance(bal); //display amount of balance } // end main

  43. Non-value Returning Method (or void method) • In some cases, a method completed its execution including of displaying an output within a method itself. • These method don’t have to return any values to a caller. Therefore, the data type declared on the method heading must be void. static void PrintLine(int n) { int i = 0; while(i < n) { Console.Write("*"); i++; } Console.WriteLine(); }

  44. The statement return in non-value returning method Likewise a value-returning method, the statement “return” in non-value returning method make the method stop its execution and bring the execution back to a calling method as the following example on the next slide.

  45. Example The value of i 3 0 1 2 3   class Program  {        static void Test(int n)    {int i = 0;while(true)      {Console.WriteLine(i);        i++;if(i > n)          return;      }    }public static void Main(string[] args)    {int a = int.Parse(Console.ReadLine());Test(a);Console.ReadLine();    }  } • Consider the methodTest and the statementwhile. • The statements in the while loop will be executed indefinitely because the condition is set to always be true. • Once i > n, the statement “return” is executed to make the method test stop its execution.

  46. Understanding Testing Write a program to read a positive integer N. Print a right triangle of size N columns x N lines with *. Enter N: 3 *** *** Enter N: 4 *** *** **** Enter N: 6 *** *** **** ***** ****** Note: Write a void method PrintTriangle(int n) to print a right triangle according to the above requirement. The methodPrintTriangle calls PrintLine to print * on each line.

  47. class Program { static void PrintLine(int count) { int k = 0; while (k < count) { Console.Write('*'); k++; } } static void PrintTrangle(int n) { int count = 1; while (count <= n) { PrintLine(count); count++; Console.WriteLine(); } } public static void Main(string[] args) { int num; Console.WriteLine("Please enter num"); num = int.Parse(Console.ReadLine()); PrintTrangle(num); Console.ReadLine(); } }

  48. Scope of variable

  49. Scope of Variable (1) A variable declared in CsharpDev is classified into 2 types : Local Variable and Global Variable (ตัวแปรส่วนกลาง). Local Variable : Local Variable is a variable declared within a method. Therefore, this type of variable can be referenced only within the method that create it. The declaration of local variable begins with Data Type and followed by variable name as following examples: double avg; char alpha; int num;

  50. Scope of Variable (2) Global Variable : is a variable declared within a class outside a boundary of any methods. The declaration of Global Variable begins with the word “static” and follows by its data type as the following example: class ClassGlobal { static int op1, op2, answer; static bool found; static string name = “C# developer”; /* Declaration of Global variable together with its initial value.*/ static void compute(int op1, int op2) { double num; ……………………………………………………….; } static void Main() { string alpha; int limit; ……………………………………………………….; } } Global Variables Local Variables of the methodcompute() Local Variables of the method Main()

More Related