method and scope of variable

86
Method and Scope of variable 01204111 Computer and Programming

Upload: tyrone

Post on 08-Feb-2016

53 views

Category:

Documents


0 download

DESCRIPTION

Method and Scope of variable. 01204111 Computer and Programming. Outline. Introduction to Method Method declaration and Calling Scope of variable. Introduction to Method. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Method and Scope of variable

Method and Scope of variable

01204111 Computer and Programming

Page 2: Method and Scope of variable

Outline

• Introduction to Method• Method declaration and

Calling• Scope of variable

Page 3: Method and Scope of variable

Introduction to MethodIntroduction 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.

Page 4: Method and Scope of variable

Types of a method)Types of a method)A method can be divided 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.

Page 5: Method and Scope of variable

Concept of writing a methodExam

ple : 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: 3*********

Enter N: 6************************************

Enter N: 6************************************

Enter N: 4****************

Enter N: 4****************

Page 6: Method and Scope of variable

Step Planning• Read integer to n, for example 4

is read to n.• Draw a rectangle using the

following steps:– Advance to line 1 – Print a line of 4 *’s.

– Advance to line 2– Print a line of 4 *’s.

– Advance to line 3– Print a line of 4 *’s.

– Advance to line 4– Print a line of 4 *’s.

****************

****************

Page 7: Method and Scope of variable

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

Page 8: Method and Scope of variable

Writing the method Main

• Now, we assume that the method PrintSquare exists. (In fact, it has not been defined yet)

static void Main(){ int n = int.Parse(Console.ReadLine()); PrintSquare(n); Console.ReadLine();}

static void Main(){ int n = int.Parse(Console.ReadLine()); PrintSquare(n); Console.ReadLine();}

โปรแกรมพิ�มพิ

สี่��เหลี่��ยม

ร�บค่�า Nพิ�มพิ

สี่��เหลี่��ยม ขนาด N x

N

This statement has not been defined yet.

This statement has not been defined yet.

Page 9: Method and Scope of variable

เมธอดแสี่ดงสี่��เหลี่��ยม• The method PrintSquare

has called the method PrintLine for N times. Each time the method PrintLine is called, it prints a line with the length of N stars.

Print a rectangle of size N

x N

Print each line with

the length of N stars

static void PrintSquare(int n){ int i = 0; while(i < n) { PrintLine(n); i++; }}

static void PrintSquare(int n){ int i = 0; while(i < n) { PrintLine(n); i++; }} This statement has not

been defined yet.This statement has not

been defined yet.

Page 10: Method and Scope of variable

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

static void PrintLine(int n){ int i = 0; while(i < n) { Console.Write("*"); i++; } Console.WriteLine();}

Page 11: Method and Scope of variable

Complete programusing 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();    }  }}

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

Method MainMethod Main

Method PrintSquareMethod PrintSquare

Method PrintLineMethod PrintLine

is a calling method (It call the method PrintSquare)

is a called method (because it was called by Main). Also it is calling method (because it calls the method PrintLine).

is a called method (It is called by PrintSquare)

Page 12: Method and Scope of variable

Method Declaration Method Declaration and Exampleand 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().

Page 13: Method and Scope of variable

Declaration of Value Returning Method

Syntax of Value-Returning Method Declaration

static data type Method name ( a parameter list ){ // Program Body (instruction part) of method}

According to the slide number 4, a method can be divided 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.

The declaration of Non-Value returning Method will be presented in the next chapter.

Page 14: Method and Scope of variable

Value-Returning Method Declaration

static double Poly(double a, double b, double c, double x){ return a*x*x + b*x + c;}

static double Poly(double a, double b, double c, double x){ return a*x*x + b*x + c;}

Data type of a

result produced by Poly

Method name :

Poly

Parameter list : a, b, c, x

The following example is the declaration of a method Poly to compute Polynomial of degree two ax2 + bx + c

Page 15: Method and Scope of variable

Location of Method Declaration• A method is declared within a class.

• A method can not declared within any other method.

using System;namespace met_examples {  class Program  {    static double Poly(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)); ……………………..;

    }  }}

Page 16: Method and Scope of variable

Component of Method Declaration

• Method Declaration consists of 2 important parts:

static double Poly(double a, double b, double c, double x){ return a*x*x + b*x + c;}

static double Poly(double a, double b, double c, double x){ return a*x*x + b*x + c;}

1. Method heading

2. Method body (collection of

instructions of a method)

Page 17: Method and Scope of variable

สี่�วนห�วของเมธอด (method header)

• 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:

static double Poly(double a, double b, double c, double x)

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.

Page 18: Method and Scope of variable

สี่�วนตั�วของเมธอด (method body)

The method body is a collection of instructions defined to compute something as stated on the heading.

The method Poly

Other method

sCalling to the method Poly to calculate a value which

was returned to a caller

Collection of instructions which was

executed to produce a

value.

Collection of instructions which was

executed to produce a

value.

Page 19: Method and Scope of variable

การน�าเมธอดไปใช้#• 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.

Page 20: Method and Scope of variable

using System;namespace met_examples{  class Program  {    static double Poly(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();    }  }}

Example of calling a method (1)

Program starts its execution

at Main.

The program consists of 2 methods: Main and Poly.

Main calls the method Poly.

Page 21: Method and Scope of variable

using System;namespace met_examples{  class Program  {    static double Poly(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();    }  }}

Example of calling a method (2)

k 3

Main sent its actual parameters (1,2,4,k) to formal parameters of Poly (a,b,c,x).

Main sent its actual parameters (1,2,4,k) to formal parameters of Poly (a,b,c,x).

a 1

b 2

c 4

x 3

19

y19

Output

19Output

19

Page 22: Method and Scope of variable

using System;namespace met_examples{  class Program  {    static double Poly(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();    }  }}

Parameter passing (1)

The important step of calling a method is parameter passing to pass (send) parameter (s) from calling to called method.

Page 23: Method and Scope of variable

   static double Poly(double a, double b, double c, double x)    {

………………………………..; } public static void Main() {

…………………………………..;       double y = Poly(1,2,4,k);

…………………………………….; }

การสี่�งพิาราม�เตัอร (2)

• 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 Parameter respectively. Therefore the number of Actual Parameters and Formal Parameters must be equal and the data type of each pair must be compatible.

Page 24: Method and Scope of variable

   static double Poly(double a, double b, double c, double x)    {

………………………………..; } public static void Main() {

………………………………;       double y = Poly(1,2,4,k);

………………………………; }

การสี่�งพิาราม�เตัอร (3)

Important remarks:• The number of Actual parameters and Formal

parameters must be equal.• Actual parameter can be variable, or constant, or

expression while Formal parameter must only be a variable whose data type is compatible with Actual parameter.

Formal Parameter

Actual Paramete

r

Page 25: Method and Scope of variable

Actual Parameter

static double Poly(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)); ……………………..;

    }

Parameter passing (4)

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

Page 26: Method and Scope of variable

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

parameterCompatible Data type of Formal

parameter

byte byte, short, int, long

float float, double

char char

string string

bool bool

Page 27: Method and Scope of variable

No matter how many Actual parameters are passed to Formal parameters, a called method always produces only 1 value which is returned to calling method.

Calling method

Called method

a

8.25*3/2

15.78

Math.sqrt(y)

abcx

Execution

statements

1 outp

ut valu

e

The output value is sent back to calling method by the statement “return”.

Page 28: Method and Scope of variable

using System;namespace met_examples{  class Program  {    static double Poly(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();    }  }}

Calling a method: Example 1

2 3 6 2What is the output of

this program ?

What is the output of

this program ?2020

Page 29: Method and Scope of variable

using System;namespace met_examples{  class Program  {    static double Poly(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();    }  }}

Calling a method: Example 2

What is the output of

this program ?

What is the output of

this program ?

2011111

2011111

Page 30: Method and Scope of variable

static void Main(string [] args){ int a = int.Parse( Console.ReadLine()); int b = int.Parse( Console.ReadLine());

Console.WriteLine(Min(a,b));}

ค่�าสี่��ง return (1)static int Min(int x, int y){ if(x < y) return x; return y;}

static int Min(int x, int y){ if(x < y) return x; return y;}

x 100

y 15

1515

Calling spot : a = 100 b = 15

The return statement send the output of the method Min back to a calling spot in the calling method.

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.

Page 31: Method and Scope of variable

ค่�าสี่��ง return (2)static int Min(int x, int y){ if(x < y) return x; return y;}

static int Min(int x, int y){ if(x < y) return x; return y;}

x 10

y 100

static void Main(string [] args){ int a = int.Parse( Console.ReadLine()); int b = int.Parse( Console.ReadLine());

Console.WriteLine(Min(a,b));}

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.

1010

The return statement send the output of the method Min back to a calling spot in the calling method.

Page 32: Method and Scope of variable

Example program of Value-Returning Method (1)Example 1 The 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 Method Main() :

• Read n and r: n คื�อ the number of distinct objects and r is the number of selected objects.• Call the method combination and pass n and r to it.

The Method combination() :• formal parameters of the combination() accept n and r from the method Main().• Call the method fac()3 times : fac(n), fac(r),and fac(n-r)

to calculate n!, r!, and n-r!• return the calculation result of n!/r!*(n – r)! to Main()

The Method fac() :• formal parameter of the method fac()accepts n from the combination(). • Calculate fac(n) and return result to the method the combination(). • Calculate fac(r) and return result to the method the combination(). • Calculate fac(n-r) and return result to the method the combination().

Page 33: Method and Scope of variable

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();

}

Page 34: Method and Scope of variable

Eample 2 The following program is to find Greatest Common Divisor (GCD) of 2 integer numbers. (The program example is on the next slide)

Remember : The Value-Returning Method returns only 1 output value to calling program.

Example program of Value-Returning Method (2)

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.

Page 35: Method and Scope of variable

static int 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

Page 36: Method and Scope of variable

Example 3 :

There are 2 types of mobile promotion :– Type A: Monthly payment 50 Baht, Free call 50

minutes and 1.5 Baht per minute for the next minutes.

– Type B: Monthly payment 150 Baht, Free call 100 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.

The advantage of dividing a program into methods is to minimize a repetitiveness of program coding as the following example:

Example program of Value-Returning Method (3)

Page 37: Method and Scope of variable

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.

    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.");      else        Console.WriteLine("Plan B is better.");      Console.ReadLine();    }

    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.");      else        Console.WriteLine("Plan B is better.");      Console.ReadLine();    }

Page 38: Method and Scope of variable

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;

จ�านี้ว้นี้นี้าที�ที��โทีรฟร�จ�านี้ว้นี้นี้าที�ที��โทีรฟร�คื�าใช้�จ�ายรายเด�อนี้คื�าใช้�จ�ายรายเด�อนี้ราคืาตั�อนี้าที�ในี้ส่�ว้นี้ที��เห้ล�อราคืาตั�อนี้าที�ในี้ส่�ว้นี้ที��เห้ล�อ

Page 39: Method and Scope of variable

A method for a fee calculation

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

    static double CalculatePrice(double monthlyFee,                                 double freeMinutes,                                 double rate,                                 double usage)    {      if(usage <= freeMinutes)        return monthlyFee;      else        return monthlyFee + (usage - freeMinutes) * rate;    }

    static double CalculatePrice(double monthlyFee,                                 double freeMinutes,                                 double rate,                                 double usage)    {      if(usage <= freeMinutes)        return monthlyFee;      else        return monthlyFee + (usage - freeMinutes) * rate;    }

Page 40: Method and Scope of variable

The Main method of a fee calculation program

• This program is shorter and more readible.

    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.");      else        Console.WriteLine("Plan B is better.");      Console.ReadLine();    }

    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.");      else        Console.WriteLine("Plan B is better.");      Console.ReadLine();    }

Page 41: Method and Scope of variable

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.Example 4 :

In this program, the methods Deposit() and Withdraw() have no Formal 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.

Example program of Value-Returning Method (4)

Page 42: Method and Scope of variable

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 Depositb = Withdraw(); // เร�ยกัใช้� Method Withdrawwhile (b > bal){

Console.WriteLine("Money is not enought!!!");Balance(bal); // เร�ยกัใช้� Procedure Balancreb = Withdraw();

}bal = bal - b;Balance(bal); //display amount of balance

} // end main

Page 43: Method and Scope of variable

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

static void PrintLine(int n){ int i = 0; while(i < n) { Console.Write("*"); i++; } Console.WriteLine();}

Page 44: Method and Scope of variable

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.

Page 45: Method and Scope of variable

Example

• Consider the method Test and the statement while.

• The statements in the while loop will be executed indefinitely because the condition is set to always be true.

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

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

30123

30123

The value of i

• Once i > n, the statement “return” is executed to make the method test stop its execution.

Page 46: Method and Scope of variable

Understanding Testing

Write a program to read a positive integer N. Print a right triangle of size N columns x N lines with *.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: 3******

Enter N: 6*********************

Enter N: 6*********************

Enter N: 4**********

Enter N: 4**********

Note: Write a void method PrintTriangle(int n) to print a right triangle according to the above requirement. The method PrintTriangle calls PrintLine to print * on each line.

Page 47: Method and Scope of variable

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();

}}

Page 48: Method and Scope of variable

Scope of variableScope of variable

Page 49: Method and Scope of variable

Scope of Variable Scope of Variable (1)(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;

Page 50: Method and Scope of variable

Scope of Variable Scope of Variable (2)(2)

 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 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:

Global Variables

Local Variables of the method compute()

Local Variables of the method Main()

Page 51: Method and Scope of variable

Differences between Local and Global Variables

Besides, the difference in declaration location, the other difference between Local variable and Global variable is the occurrence and termination of their values.

Value of Local variable is initialized and terminated within a method that create it. While a value of Global variable is initialized within a class , outside a boundary of any method. Its value will be terminated when the program stop its execution.

Once, a Global variable is declared, it belongs to a public. (It does not belong to any particular method). Therefore, every method can reference to it. Programmer must be careful when using global variable because its current value will be executed continuously cross over methods that reference to it.

Page 52: Method and Scope of variable

Local variable in a methodA local variable may be needed especially in a complicate method to keep temporary value during its execution as the following example:

cbabe

a

c /

2

static double MyFunc(double a, double b, double c){ double x, y, z;   x = 2 * Math.Pow(a,b); y = c / x;  z = Math.Exp(a + b/c);   return  y + z;}

static double MyFunc(double a, double b, double c){ double x, y, z;   x = 2 * Math.Pow(a,b); y = c / x;  z = Math.Exp(a + b/c);   return  y + z;}

Variables which are declared in a method and including of all formal parameters are Local variables of that method.

Variables which are declared in a method and including of all formal parameters are Local variables of that method.

Local variables of the method MyFunc are a, b, c, x, y, and z

Local variables of the method MyFunc are a, b, c, x, y, and z

Page 53: Method and Scope of variable

Local variable

Variables which are declared in a method, including of all formal parameters are Local variable of the method.

static double MyFunc(double a, double b, double c){ double x, y, z;   x = 2 * Math.Pow(a,b); y = c / x;  z = Math.Exp(a + b/c);   return  y + z;}

static double MyFunc(double a, double b, double c){ double x, y, z;   x = 2 * Math.Pow(a,b); y = c / x;  z = Math.Exp(a + b/c);   return  y + z;} The Local variables

of the method MyFunc are a, b, c, x, y, and z

The Local variables of the method MyFunc are a, b, c, x, y, and z

Page 54: Method and Scope of variable

Being a “LOCAL"

MethodA

MethodB

MethodCaa bbzz

sumsum tt

countcount

aa

bbzz

tt

ttnn

kk

Local variables declared in difference methods are not involved among the others even though their names may be duplicated.

Page 55: Method and Scope of variable

Consider the following program and pay attention on the method structure and its local variables.

  class Program  {     static int C(int a, int b)     {       int t = 0;       int n = b;       while((n<=a) && (a % n == 0)) {         t++;  n *= b;       }       return t;    }        public static void Main(string[] args)    {      int n = int.Parse(Console.ReadLine());       int b = int.Parse(Console.ReadLine());       int m = C(n,b);       Console.WriteLine("{0} is divisible by {1} ^ {2}.",                         n,b,m);       Console.ReadLine();    }  }

  class Program  {     static int C(int a, int b)     {       int t = 0;       int n = b;       while((n<=a) && (a % n == 0)) {         t++;  n *= b;       }       return t;    }        public static void Main(string[] args)    {      int n = int.Parse(Console.ReadLine());       int b = int.Parse(Console.ReadLine());       int m = C(n,b);       Console.WriteLine("{0} is divisible by {1} ^ {2}.",                         n,b,m);       Console.ReadLine();    }  }

ตั�วอย�าง 1

The local variables of the method Care a, b, t, and n.

The local variables of the method Main are n, b, and m.

What are the local variables of both methods?What are the local variables of both methods?

Page 56: Method and Scope of variable

ตั�วอย�าง 1

  class Program  {     static int C (int  a, int  b)     {       int  t = 0;       int  n = b;       while((n<=a) && (a % n == 0)) {         t++;  n *= b;       }       return t;    } 

    public static void Main(string[] args)    {      int  n = int.Parse(Console.ReadLine());       int  b = int.Parse(Console.ReadLine());       int  m = C(n,b);       Console.WriteLine("{0} is divisible by {1} ^ {2}.",                         n,b,m);       Console.ReadLine();    }  }

  class Program  {     static int C (int  a, int  b)     {       int  t = 0;       int  n = b;       while((n<=a) && (a % n == 0)) {         t++;  n *= b;       }       return t;    } 

    public static void Main(string[] args)    {      int  n = int.Parse(Console.ReadLine());       int  b = int.Parse(Console.ReadLine());       int  m = C(n,b);       Console.WriteLine("{0} is divisible by {1} ^ {2}.",                         n,b,m);       Console.ReadLine();    }  }

Both b are different variables. One is the local variable of Main which send its value to the other b which is formal parameter of the method C.

Both n in the method C and n in the method Main are different variables.

Page 57: Method and Scope of variable

Example 2

  class Program  { static int n;     static int C(int  a, int  b)     {       int  t = 0;       n = b;       while((n<=a) && (a % n == 0)) {         t++;  n *= b;       }       return t;    } 

    public static void Main(string[] args)    {      int n = int.Parse(Console.ReadLine());       int  b = int.Parse(Console.ReadLine());       int  m = C(n,b);       Console.WriteLine("{0} is divisible by {1} ^ {2}.", n, b, m);       Console.ReadLine();    }  }

  class Program  { static int n;     static int C(int  a, int  b)     {       int  t = 0;       n = b;       while((n<=a) && (a % n == 0)) {         t++;  n *= b;       }       return t;    } 

    public static void Main(string[] args)    {      int n = int.Parse(Console.ReadLine());       int  b = int.Parse(Console.ReadLine());       int  m = C(n,b);       Console.WriteLine("{0} is divisible by {1} ^ {2}.", n, b, m);       Console.ReadLine();    }  }

Both n are not the same variables. The variable n in the method C is Global whereas n in the method Main is Local variable of Main itself.

Both n are the same variables. It is Global variable of the program. The method C does not declare n of its own, therefore n seen in the method C is Global.

Page 58: Method and Scope of variable

  class Program  {    static void SuperSum(int price)    {      totalPrice += price;    }        public static void Main(string[] args)    {      int totalPrice = 0;      int p = int.Parse(Console.ReadLine());      while(p!=0)      {          SuperSum(p);          p = int.Parse(Console.ReadLine());      }      Console.WriteLine(totalPrice);    }  }

  class Program  {    static void SuperSum(int price)    {      totalPrice += price;    }        public static void Main(string[] args)    {      int totalPrice = 0;      int p = int.Parse(Console.ReadLine());      while(p!=0)      {          SuperSum(p);          p = int.Parse(Console.ReadLine());      }      Console.WriteLine(totalPrice);    }  }

The name 'totalPrice' does not exist in the current context.

The method SuperSum can not use the variable totalPrice because this variable is a Local of the method Main(). Therefore, it should be used in Main only.

The method SuperSum can not use the variable totalPrice because this variable is a Local of the method Main(). Therefore, it should be used in Main only.

Types of variable : Causes of errors

A message of syntax error as the above is prompted as soon as the program is compiled because the declaration of the totalPrice doesn’t exist in SuperSum . On the other hand, it is not Global variable either because it belongs to the method Main.

Page 59: Method and Scope of variable

  class Program  {    static void SuperSum(int price)    {      int totalPrice += price;    }        public static void Main(string[] args)    {      int totalPrice = 0;      int p = int.Parse(Console.ReadLine());      while(p!=0)      {          SuperSum(p);          p = int.Parse(Console.ReadLine());      }      Console.WriteLine(totalPrice);    }  }

  class Program  {    static void SuperSum(int price)    {      int totalPrice += price;    }        public static void Main(string[] args)    {      int totalPrice = 0;      int p = int.Parse(Console.ReadLine());      while(p!=0)      {          SuperSum(p);          p = int.Parse(Console.ReadLine());      }      Console.WriteLine(totalPrice);    }  }

Program correction

Syntax error of the program in previous slide is corrected by adding the declaration of totalprice as a local variable of SuperSum. The totalprice in SuperSum and in Main are not the same variables.

The statement Console.WriteLine(totalprice) in Main displayed 0 because the totalprice is initialized to 0 and no any other statements have its value changed.

Page 60: Method and Scope of variable

Sharing of a variable among methods

Declaration as a Global can make a variable ready to be shared among methods as the example on the next slide.A global variable must be used with care because this type of variable continuously carries its latest value cross over methods that referenced to it.

totalPricetotalPrice

Main SuperSum

totalPricetotalPrice totalPricetotalPrice

Page 61: Method and Scope of variable

Global variable

This program is modified by changing a declaration of totalPrice from the local of Main and SuperSum to the Global instead. Now, the variable totalPrice referenced in any methods is Global totalPrice (It is not a local totalPrice any more.)

  class Program  {    static int totalPrice;    static void SuperSum(int price)    {      totalPrice += price;    }        public static void Main(string[] args)    {      totalPrice = 0;      int p = int.Parse(Console.ReadLine());      while(p!=0)      {          SuperSum(p);          p = int.Parse(Console.ReadLine());      }      Console.WriteLine(totalPrice);    }  }

  class Program  {    static int totalPrice;    static void SuperSum(int price)    {      totalPrice += price;    }        public static void Main(string[] args)    {      totalPrice = 0;      int p = int.Parse(Console.ReadLine());      while(p!=0)      {          SuperSum(p);          p = int.Parse(Console.ReadLine());      }      Console.WriteLine(totalPrice);    }  }

Page 62: Method and Scope of variable

Global variable Declaration• A Global variable is declared within a

class, outside a boundary of any method. This type of variable belongs to a public. It can be referenced in every method in a program.

• Format of declaration : A global variable declaration must start with the keyword “static” , follow by variable name and ended with semi-colon.

static data type Variable name ;OR

static data type Variable name = initial value ; /* global declaration with its initial value */

Page 63: Method and Scope of variable

Example• A grocery store sell pen and

launch–Price of a pen is 5 baht.–Launch menu consists of 2 items : rice with omelet and rice with chicken and basil

• Write a program to show a menu and calculate total price sold.

Page 64: Method and Scope of variable

Overview

• We declares a global variable totalIncome to keep total revenue which will be displayed at the end of the program.

• We divide our work into 2 parts which are SaleFood and Sale Pencil.

  class Program  {    static int totalIncome = 0;

    static void SaleFood()    { /* be omitted */    }    static void SalePencil()    { /* be omitted */    }

    public static void Main(string[] args)    { string ans;      do {        Console.Write("Eat, Write, or Quit (E/W/Q): ");        ans = Console.ReadLine();        if(ans == "E")          SaleFood();        else if(ans == "W")          SalePencil();      } while(ans != "Q");      Console.WriteLine("Total income = {0}",  totalIncome);    }  }

  class Program  {    static int totalIncome = 0;

    static void SaleFood()    { /* be omitted */    }    static void SalePencil()    { /* be omitted */    }

    public static void Main(string[] args)    { string ans;      do {        Console.Write("Eat, Write, or Quit (E/W/Q): ");        ans = Console.ReadLine();        if(ans == "E")          SaleFood();        else if(ans == "W")          SalePencil();      } while(ans != "Q");      Console.WriteLine("Total income = {0}",  totalIncome);    }  }

Page 65: Method and Scope of variable

The SaleFoof Method    static void SaleFood()    {      Console.Write("Omlet or Chicken Kraprao (O/C): ");      string ans = Console.ReadLine();      if(ans == "O")      {        Console.WriteLine("The price is 10 baht.  Thanks");        totalIncome += 10;      }      else if(ans == "C")      {        Console.WriteLine("The price is 15 baht.  Thanks");        totalIncome += 15;              }    }

    static void SaleFood()    {      Console.Write("Omlet or Chicken Kraprao (O/C): ");      string ans = Console.ReadLine();      if(ans == "O")      {        Console.WriteLine("The price is 10 baht.  Thanks");        totalIncome += 10;      }      else if(ans == "C")      {        Console.WriteLine("The price is 15 baht.  Thanks");        totalIncome += 15;              }    }

This method can reference totalIncome without declaration because this variable was already declared in the class as Global variable.

Page 66: Method and Scope of variable

Global Variable obscurity

• If a local variable of a method has duplicate name with a global variable, the variable name referenced in this method must be a local variable because local variable usually obscures global variable as following examples:

Page 67: Method and Scope of variable

  namespace ConsProc7Global {

class Class1{

static int x, y, z,sum, res; 

static void PRG1(){

sum = sum + res;res = res % 5;Console.WriteLine("In PRG1, sum = {0}", sum);Console.WriteLine("In PRG1, res = {0}", res);

static void PRG2(){

int sum;sum = res * 2;Console.WriteLine("In PRG2, sum = {0}", sum);

static void Main(string[] args){

x = 8 ; y = 15; z = 30;sum = x + y + z;res = x * y;Console.WriteLine("In Main(), sum = {0}", sum);Console.WriteLine("In Main(), res = {0}", res);PRG1();PRG2();Console.WriteLine("Back to Main(), sum = {0}", sum);

}}

 }

Example 1 : an explanation is on the next slide.All variables

referenced in this method are Global variables because there are not any variables declared in the method itself. A variable sum in this method is local variable whereas res is a global variable.

All variables referenced in this method are Global variables because there are not any variables declared in the method itself.

Page 68: Method and Scope of variable

From the example 1 : (The program is on the previous slide.)The Global Variables of this program are declared within a class, outside the boundary of any methods. static int x, y, z,sum, res;In Main() : No Local variables declaration in the method itself. Therefore, all variables referenced in the method Main() are Global Variables. In PRG1() : No Local variables declaration in the method itself. Therefore, all variables referenced in the method PRG1() are Global Variables. In PRG2() : A variable sum is local variable because it ‘s declared in the method. The variable res is Global Variable.

In the next slide, for better understanding, let’s trace each variable value of this program.

Page 69: Method and Scope of variable

แกะรอยค่�าของตั�วแปรแตั�ลี่ะตั�วของตั�วอย�างที่�� 1 พิร#อมที่�&งเหตั'ผลี่สี่น�บสี่น'น1. At Main() :

Console.WriteLine("In Main(), sum = {0}", sum); value of sum is 53Console.WriteLine("In Main(), res = {0}", res); value of res is 120

2. At PRG1() :Console.WriteLine("In PRG1(),sum = {0}", sum); value of sum is 173Console.WriteLine("In PRG1(),res = {0}", res); value of res is 0(The latest value of sum and res are 53 and 120 respectively. The

execution in this method make their latest values become 173 and 0 respectively.

3. At PRG2() :Console.WriteLine("In PRG2(), sum = {0}", sum); คื�า sum คื�อ 0(This sum is Local variable of PRG2() itself. Its value is

calculated by the expression res * 2. The latest value of res is 0. Consequently, the value of sum is 0).

4. At Main() :Console.WriteLine("Back to Main(),sum = {0}",sum); value of sum is 173(This sum is Global variable. Its latest value occurs from the

execution in PRG1().

Page 70: Method and Scope of variable

PRG1()

PRG2()

Main()

Local variable: sumGlobal variable: res

Local variable: ไม�ม�Global variable: sum, res

Local variable: ไม�ม�Global variable: x, y, z, sum, res

Page 71: Method and Scope of variable

class ClassGloba2{ static int op1, op2, answer;  static void Compute(int op1, int op2) {

int i = 1; 

answer = 1;while (i <= op2) {

answer = op1 * answer;i = i+1;

} } // end of compute  static void Main(string[] args){

Console.WriteLine("Enter 2 numbers"); op1 = int.Parse(Console.ReadLine()); op2 = int.Parse(Console.ReadLine()); Compute(op1, op2); answer = answer/2; Console.WriteLine("Back to Main(), final value =

{0}", answer);}

}

Example 2The variables

op1 and op2 referenced in Main() and the variables op1 and op 2 declared in the Compute() are different variables even though theirs may duplicate. The variables op1 and op2 referenced in Main() are Global variable whereas op1 and op2 in Compute() are Local variable .

Page 72: Method and Scope of variable

Tracing of variables in the example 2In the example 2, the variable answer is

Global, therefore it can be referenced in both Main() and Compute(). Its current value must be changed according to the execution within the method to which it was referenced.

1. When the execution is in the method Main() , there is a call to the method Compute() and the actual parameter op1 and op2 are passes to the Computer() (Suppose that op1 = 5 and op2 = 3 ). The last reference to answer in the Compute() made its latest value = 125.

2. When the execution returned back to Main(), the latest value (125) of answer was taken in to the execution of being divided by 2. Therefore, its latest value would be 62.

3. If there is an execution in another method that reference to answer , its latest value (62) is used as an initial value to be executed in that method continuously.

Page 73: Method and Scope of variable

Advantages of Being Local

• Local variables in different methods do not get involved among the other. Testing the execution in a specific method can be done without concerning other methods.

• The complexity of a program can be reduced.

Page 74: Method and Scope of variable

Exercise

• What does this method do ?     static int C(int a, int b)     {       int t = 0;       int n = b;       while((n<=a) && (a % n == 0)) {         t++;  n *= b;       }       return t;    }

    static int C(int a, int b)     {       int t = 0;       int n = b;       while((n<=a) && (a % n == 0)) {         t++;  n *= b;       }       return t;    }

Page 75: Method and Scope of variable

Hint

• What does this program do ?     static int C(int a, int b)     {       int t = 0;       int n = b;       while((n<=a) && (a % n == 0)) {         t++;  n *= b;       }       return t;    }

    static int C(int a, int b)     {       int t = 0;       int n = b;       while((n<=a) && (a % n == 0)) {         t++;  n *= b;       }       return t;    }

Let’s try• C(1100, 10)• C(40, 2)

Let’s try• C(1100, 10)• C(40, 2)

Page 76: Method and Scope of variable

ม'มน�กค่�ด: เฉลี่ย (1)

• เมธอด C(int a, int b)คื�านี้ว้ณ กั�าล�ง x ที��มากัที��ส่(ดของ b ที��ที�าให้� bx ย�งห้าร a ลงตั�ว้

• ยกัตั�ว้อย�างเช้�นี้ C(m, 10) คื�านี้ว้ณว้�า m ม�ศู+นี้ย,ลงที�ายกั��ตั�ว้เม��อเข�ยนี้เป-นี้เลขฐานี้ส่/บ

Page 77: Method and Scope of variable

Solution (2)Method

C(int a, int b)

To compute the greatest power (x) of b that make bx is divisible by a.

Once, we understand the execution of this method, its details can be hidden by clicking on [–] button on the left side of the program. Then, we can step forward to continuously examine other parts.

Page 78: Method and Scope of variable

Hiding details in CSharp Dev• With an idea of hiding detail, we can hide method

body (collection of statements) by clicking on [–] button at the left hand side of a program.

Page 79: Method and Scope of variable

Exercise• Testing the following program:  class Program  {        static int x = 0;    static void Test(int y)    {      x = y + 1;      Console.WriteLine(x);    }    public static void Main(string[] args)    {      Console.WriteLine(x);      Test(10);      Console.WriteLine(x);          }  }

  class Program  {        static int x = 0;    static void Test(int y)    {      x = y + 1;      Console.WriteLine(x);    }    public static void Main(string[] args)    {      Console.WriteLine(x);      Test(10);      Console.WriteLine(x);          }  }

01111

01111

output

What is the output of this program?

Page 80: Method and Scope of variable

Global vs Local Variable

Modify the following program by inserting

int x;  class Program  {        static int x = 0;    static void Test(int y)    {      int x;      x = y + 1;      Console.WriteLine(x);    }    public static void Main(string[] args)    {      Console.WriteLine(x);      Test(10);      Console.WriteLine(x);          }  }

  class Program  {        static int x = 0;    static void Test(int y)    {      int x;      x = y + 1;      Console.WriteLine(x);    }    public static void Main(string[] args)    {      Console.WriteLine(x);      Test(10);      Console.WriteLine(x);          }  }

0110

0110

Output of the program

Why the program displays outputs as shown above?

The variable x, which was inserted , make x in the statement x = y + 1 become local. Consequently, the value changed of the local x in Test doesn’t have any effect on the global x in Main any more.

Page 81: Method and Scope of variable

Variable within a block (1)

Besides, being declared within a method, a local variable can be declared within a block as well.

int n = int.Parse(Console.ReadLine());int i = 0;while(i < n){ int a = 0; int b = 0; while(b < i) { a += b; b++; } Console.WriteLine(a);}

Both a and b are local variables within a block of while. They can be referenced only within the block . Being referenced outside the block are violation and make the program error.

Both a and b are local variables within a block of while. They can be referenced only within the block . Being referenced outside the block are violation and make the program error.

Page 82: Method and Scope of variable

Variable within a block (2)

The variables, which are declared within a block, must be used in that block only. Being referenced outside the block causes a syntax error.

int n = int.Parse(Console.ReadLine());int i = 0;while(i < n){ int a = 0; int b = 0; while(b < i) { a += b; b++; } Console.WriteLine(a);}

Console.WriteLine(b);

This statement causes an error because, the variable a and b are local variables within a block of while. Therefore, they can not be referenced outside the boundary of that block.

Page 83: Method and Scope of variable

Conclusion : Scope of variable

• ตั�าแห้นี้�งในี้โปรแกัรมที��ตั�ว้แปรห้นี้0�ง ๆ ส่ามารถ้ถ้+กัอ�างถ้0งได� จะเร�ยกัว้�าขอบเขตัของตั�วแปรนี้��นี้ ๆ

• ตั�ว้แปรที��ประกัาศูในี้เมธอดม�กัฎของขอบเขตัด�งนี้��– ตั�ว้แปรจะเร/�มปรากัฏ (และอ�างถ้0งได� ) ตั��งแตั�จ(ดที��ถ้+กัประกัาศู– ตั�ว้แปรจะอ�างถ้0งได�จนี้กัระที��งห้มดขอบเขตัของบล4อคืที��ถ้+กัประกัาศู

• The boundary in which a variable can be referenced, is called scope of that variable.

• Scope rules of a variable declared within a method :• A variable can be referenced starting

from its declaration position until the end of that block.

• Being referenced beyond a block is prohibited.

Page 84: Method and Scope of variable

Example      do {        Console.Write("Eat, write, or quit (E/W/Q): ");        string ans = Console.ReadLine();        if(ans == "E")          SaleFood();        else if(ans == "W")          SalePencil();      } while(ans != "Q");

      do {        Console.Write("Eat, write, or quit (E/W/Q): ");        string ans = Console.ReadLine();        if(ans == "E")          SaleFood();        else if(ans == "W")          SalePencil();      } while(ans != "Q");

The variable ans is declared within a block. Its scope is bounded within a block (starting from its declaration position). It can not be referenced outside a block (after the condition while).

The variable ans is referenced outside its scope. Consequently, syntax error occurs.

Page 85: Method and Scope of variable

“Warning”

• ขอบเขตัของตั�ว้แปรที�องถ้/�นี้ที��ประกัาศูภายในี้บล4อกัจะเป-นี้ไปตัามกัฎที��ว้ไปของขอบเขตัของตั�ว้แปร

• อย�างไรกั4ตัามตั�ว้แปรที�องถ้/�นี้ที��ประกัาศูภายในี้บล4อคืจะไม�ส่ามารถ้บดบ�งตั�ว้แปรที�องถ้/�นี้ที��ประกัาศูในี้เมธอดได�

static void Test(int a){ int x = a; int j = 0; while(x < a) { int j = x; Console.WriteLine(j); x--; }}

static void Test(int a){ int x = a; int j = 0; while(x < a) { int j = x; Console.WriteLine(j); x--; }}

• Scope of local variable declared within a block must comply with the general rules of variable.

• However, a local variable declared within a block can not obscure the one that declared within a method.

An error occurs because the variable j declared within a block obscure the j declared within a method.

An error occurs because the variable j declared within a block obscure the j declared within a method.

Page 86: Method and Scope of variable

ConclusionConclusion

• เราส่ามารถ้ใช้�เมธอดในี้กัาร– ลี่ดค่วามซั�บซั#อนของโปรแกรม ตั�ว้แปรม�ขอบเขตักัารใช้�งานี้ที��เฉพาะเจาะจง

ที�าให้�เราส่ามารถ้พ/จารณางานี้เป-นี้ส่�ว้นี้ย�อย ๆ แยกัจากักั�นี้ได�– ลี่ดค่วามซั�&าซั#อนของโปรแกรม ที�าให้�เราส่ามารถ้รว้บรว้มโปรแกัรมที��

เห้ม�อนี้กั�นี้ ห้ร�อคืล�ายกั�นี้มาไว้�ที��เมธอดเด�ยว้ เพ��อให้�ง�ายตั�อกัารแกั�ไข

The objectives of using a method :• To minimize the complexity of a program by dividing it into several parts. A variable has its own specific scope. Programmer can check an execution of each method separately.• To avoid writing some part of statements repeatedly. Instead, programmer should collect these statements and insert them into a method which can be called whenever the same calculation pattern is needed.