Method and Scope of variable 01204111 Computer and
Method and Scope of variable 01204111 Computer and Programming
Outline • Introduction to Method • Method declaration and Calling • Scope of variable
Introduction to 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.
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.
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 ****** ******
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.
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
Writing the method Main • Now, we assume that the method Print. Square exists. (In fact, it has not been defined yet) โปรแกรมพมพ สเหลย ม รบคา N พมพสเห ลยม ขนาด N x N static void Main() { int n = int. Parse(Console. Read. Line()); Print. Square(n); Console. Read. Line; () { This statement has not been defined yet.
เมธอดแสดงสเหลยม • The method Print. Square has called the method Print. Line for N times. Each time the method Print. Line is called, it prints a line with the length of N stars. static void Print. Square(int n) { int i = 0; while(i < n) { Print. Line(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.
The method Print. Line • Once the method Print. Line is called (by the method Print. Square), 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 Print. Line(int n) { int i = 0; while(i < n) { Console. Write("*"); i++; } Console. Write. Line(); }
using System; namespace box 1 { class Program { static void Print. Line(int n) { int i = 0; while(i < n) { Console. Write("*"); i++; } Console. Write. Line(); } static void Print. Square(int n) { int i = 0; while(i < n) { Print. Line(n); i++; } } public static void Main(string[] args) { int n = int. Parse(Console. Read. Line()); Print. Square(n); Console. Read. Line(); } } } Complete program Method Print. Line is a called method) It is called by Print. Square( Method Print. Square is a called method (because it was called by Main). Also it is calling method (because it calls the method Print. Line). Method Main is a calling method )It call the method Print. Square(
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(), Print. Square() and Print. Line().
Declaration of Value Returning 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. 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.
Value-Returning Method Declaration The following example is the declaration of a method Poly to compute Polynomial of degree two ax 2 + 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
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)); …………. . ; } } }
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)
สวนหวของเมธอด (method header( static double Poly(double a, double b, double c, double x) The objective of 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: The method Poly(double a, double b, double c, double x) compute the Polynomial of degree two ax 2 + bx + c.
สวนตวของเมธอด (method body( The method body is a collection of instructions defined to compute something as stated on the heading. Other methods Calling to the method Poly to calculate a value which was returned to a caller The method Poly Collection of instructions which was executed to produce a value.
การนำเมธอดไปใช • 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. Write. Line(y); Console. Read. Line(); } Therefore, we call the method Main “Calling method” and call the method Poly “Called method” because it is called by Main.
Example of calling a method (1) using System; The program consists of 2 namespace met_examples { methods: Main and Poly. class Program { static double Poly(double a, double b, double c, double x) { return a*x*x + b*x + c; } public static void Main() Program starts its { execution at Main. double k = 3; double y = Poly(1, 2, 4, k); Console. Write. Line(y); Main calls the method Poly. Console. Read. Line(); } } }
Example of calling a method (2) using System; namespace met_examples Main sent its actual parameters (1, 2, 4, k) to { formal parameters of Poly (a, b, c, x). class Program { static double Poly(double a, double b, double c, double x) { 19 return a*x*x + b*x + c; } public static void Main() { double k = 3; double y = Poly(1, 2, 4, k); Console. Write. Line(y); Console. Read. Line(); } Output } } 19 k y 3 19 a b c x 1 2 4 3
Parameter passing (1) 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); The important step of calling a Console. Write. Line(y); method is parameter passing Console. Read. Line(); to pass (send) parameter (s) } } from calling to called method. }
การสงพารามเตอร (2( static double Poly(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 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.
การสงพารามเตอร (3( Formal Parameter static double Poly(double a, double b, double c, double x) { ………………. . ; } public static void Main() Actual Parameter } ; ……………… double y = Poly(1, 2, 4, k); ………………; } 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.
Parameter passing(4) Formal 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)); …………. . ; } Actual Parameter passing of the 1 st pair is a sending-accepting variable to variable. Parameter passing of the 2 nd pair is a sending-accepting constant to variable. Parameter passing of the 3 rd pair is a sending-accepting an expression (3/2*8. 25) to variable. Parameter passing of the 4 th pair is a sending-accepting a function expression )math. sqrt) to 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 parameter byte float char string bool Compatible Data type of Formal parameter byte, short, int, long float, double char string bool
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. Called method Calling method a 15. 78 8. 25*3/2 Math. sqrt(y) a b c x Execution statements The output value is sent back to calling method by the statement “return”. 1 output value
Calling a method: Example 1 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); What is the output of Console. Write. Line(y); this program ? Console. Read. Line(); } 20 } } 2 3 6 2
Calling a method: Example 2 using System; namespace met_examples { class Program { static double Poly(double a, double b, double c, double x) { /* ����� */ } public static void Main() { What is the output of double k = 3; double y = Poly(2, k, k+3, 2); this program ? Console. Write. Line(y); y = Poly(1, 1, 1, 10); Console. Write. Line(y); 20 Console. Write. Line(Poly(1, 2, 3, 2)); 111 Console. Read. Line(); 11 } } }
คำสง return (1( static int Min(int x, int y) { if(x < y) x 100 return x; y 15 return y; } The return statement send the output of the method Min back to a calling spot in the calling method. 15 static void Main(string [] args) { int a = int. Parse( Console. Read. Line()); int b = int. Parse( Console. Read. Line()); Calling spot : a = 100 Console. Write. Line(Min(a, b)); 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. Write. Line (Min (a, b)); at the method Main.
คำสง return (2( static int Min(int x, int y) { x 10 if(x < y) return x; y 100 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. Read. Line()); int b = int. Parse( Console. Read. Line()); Calling spot : a = 10 Console. Write. Line(Min(a, b)); 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. Write. Line (Min (a, b)); at the method Main.
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().
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. Write. Line("Enter the total of n"); n = int. Parse(Console. Read. Line()); Console. Write. Line("Enter the number selected"); r = int. Parse(Console. Read. Line()); nummeth = combination(n, r); Console. Write. Line(nummeth); Console. Read. Line(); {
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 the next slide( This program divided its execution into 2 methods which are Main and Greatest. Common. The method Main passes (sends) 2 Actual parameters to the method Greatest. Common 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.
static int greatest. Common(int a, int b) { int temp; if (a<b){ Formal Parameters 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; } Actual. Parameters } // end greatest. Common static void Main(string[] args){ int a, b; Console. Write("Enter the first integer numbers : "); a = int. Parse(Console. Read. Line()); Console. Write("Enter the second integer numbers : "); b = int. Parse(Console. Read. Line()); Console. Write. Line("GCD of {0} and {1} = {2}, a, b, greatest. Common(a, b)); }// end Main()
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: 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.
public static void Main(string[] args) { Console. Write("Enter expected usage: "); int u = int. Parse(Console. Read. Line()); double price 1; if(u <= 50) price 1 = 50; else price 1 = 50 + (u - 50)*1. 5; double price 2; if(u <= 100) price 2 = 150; else price 2 = 150 + (u - 100)*1. 0; if(price 1 < price 2) Console. Write. Line("Plan A is better. "); else Console. Write. Line("Plan B is better. "); Console. Read. Line(); } 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.
The same calculation patterns of both promotion types double price 1; if(u <= 50) price 1 = 50; else price 1 = 50 + (u - 50)*1. 5; double price 2; if(u <= 100) price 2 = 150; else price 2 = 150 + (u -100)*1. 0; ราคาตอนาทในสวนทเหลอ จำนวนนาททโทรฟร คาใชจายรายเดอน • 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.
A method for a fee calculation static double Calculate. Price(double monthly. Fee, double free. Minutes, double rate, double usage) { if(usage <= free. Minutes) return monthly. Fee; else return monthly. Fee + (usage - free. Minutes) * rate; } • The calculation parts of this program are collected within a method named Calculate. Price with its parameter list : monthly. Fee, free. Minutes, rate and usage to which the calling method can send any other sets of different values.
The Main method of a fee calculation program public static void Main(string[] args) { Console. Write("Enter expected usage: "); int u = int. Parse(Console. Read. Line()); double price 1 = Calculate. Price(50, 1. 5, u); double price 2 = Calculate. Price(150, 100, 1. 0, u); if(price 1 < price 2) Console. Write. Line("Plan A is better. "); else Console. Write. Line("Plan B is better. "); Console. Read. Line(); } • This program is shorter and more readible.
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. 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.
static int Deposit() { int s; Console. Write("Amount to deposit : "); s = int. Parse(Console. Read. Line()); return s; } // end Deposit static int Withdraw(){ int s; Console. Write("Amount to withdraw : "); s = int. Parse(Console. Read. Line()); return s; } // end Withdraw static void Balance (int bal){ Console. Write. Line ("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. Write. Line("Money is not enought!!!"); Balance(bal); // ���� Procedure Balancre b = Withdraw(); } bal = bal - b; Balance(bal); //display amount of balance } // end main
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 Print. Line(int n) { int i = 0; while(i < n) { Console. Write("*"); i++; } Console. Write. Line(); }
The statement return in non-value returning method Likewise a value-returning method, the statement “return” in nonvalue 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.
Example class Program { static void Test(int n) { int i = 0; while(true) { Console. Write. Line(i); i++; if(i > n) return; } } public static void Main(string[] args) { int a = int. Parse(Console. Read. Line()); Test(a); Console. Read. Line(); } } The value of i 3 0 1 2 3 • 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. • Once i > n, the statement “return” is executed to make the method test stop its execution.
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 Print. Triangle(int n) to print a right triangle according to the above requirement. The method Print. Triangle calls Print. Line to print * on each line.
class Program } static void Print. Line(int count) } int k = 0; while (k < count) } Console. Write('*'); k++; { { static void Print. Trangle(int n) } int count = 1; while (count <= n) } Print. Line(count); count++; Console. Write. Line(); { { public static void Main(string[] args) } int num; Console. Write. Line("Please enter num"); num = int. Parse(Console. Read. Line()); Print. Trangle(num); Console. Read. Line(); { {
Scope of variable
Scope of Variable (1) A variable declared in Csharp. Dev 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;
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 Class. Global Variables { static int op 1, op 2, answer; static bool found; static string name = “C# developer”; /* Declaration of Global variable together with its initial value. */ static void compute(int op 1, int op 2) { Local Variables of the double num; ……………………………. ; method compute() } static void Main() { string alpha; int limit; ……………………………. ; } } Local Variables of the method Main()
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.
Local variable in a method A local variable may be needed especially in a complicate method to keep temporary value during its execution as the following example: Local variables of the method My. Func are a, b, c, x, y, and z static double My. Func(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); Variables which are declared in a method and including of all formal parameters are Local return y + z; } variables of that method.
Local variable Variables which are declared in a method, including of all formal parameters are Local variable of the method. static double My. Func(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 My. Func are a, b, c, x, y, and z
Being a“ LOCAL" Local variables declared in difference methods are not involved among the others even though their names may be duplicated. Method. B a Method. A a b z sum count t n Method. C k b z t t
ตวอยาง 1 class Program { Consider the following static int C(int a, int b) program and pay attention on { int t = 0; the method structure and its int n = b; local variables. while((n<=a) && (a % n == 0)) { t++; n *= b; The local variables of the method C } are a, b, t, and n. return t; } public static void Main(string[] args) The local variables of the { int n = int. Parse(Console. Read. Line()); method Main are n, b, and m. int b = int. Parse(Console. Read. Line()); int m = C(n, b); Console. Write. Line("{0} is divisible by {1} ^ {2}. ", n, b, m); Console. Read. Line(); } } What are the local variables of both methods?
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. Read. Line()); int b = int. Parse(Console. Read. Line()); int m = C(n, b); Console. Write. Line("{0} is divisible by {1} ^ {2}. ", n, b, m); Console. Read. Line(); } } ตวอยาง 1 Both n in the method C and n in the method Main are different variables. 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.
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. Read. Line()); int b = int. Parse(Console. Read. Line()); int m = C(n, b); Console. Write. Line("{0} is divisible by {1} ^ {2}. ", n, b, m); Console. Read. Line(); } } Example 2 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. 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.
The name 'total. Price' does not exist in the current context. class Program { static void Super. Sum(int price) { total. Price += price; } public static void Main(string[] args) { int total. Price = 0; int p = int. Parse(Console. Read. Line()); while(p!=0) { Super. Sum(p); p = int. Parse(Console. Read. Line()); } Console. Write. Line(total. Price); } } 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 total. Price doesn’t exist in Super. Sum. On the other hand, it is not Global variable either because it belongs to the method Main. The method Super. Sum can not use the variable total. Price because this variable is a Local of the method Main(). Therefore, it should be used in Main only.
Program correction class Program { static void Super. Sum(int price) { int total. Price += price; } public static void Main(string[] args) { int total. Price = 0; int p = int. Parse(Console. Read. Line()); while(p!=0) { Super. Sum(p); p = int. Parse(Console. Read. Line()); } Console. Write. Line(total. Price); } } Syntax error of the program in previous slide is corrected by adding the declaration of totalprice as a local variable of Super. Sum. The totalprice in Super. Sum and in Main are not the same variables. The statement Console. Write. Line(totalprice) in Main displayed 0 because the totalprice is initialized to 0 and no any other statements have its value changed.
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. total. Price Main Super. Sum total. Price
class Program { static int total. Price; static void Super. Sum(int price) { total. Price += price; } public static void Main(string[] args) { total. Price = 0; int p = int. Parse(Console. Read. Line()); while(p!=0) { Super. Sum(p); p = int. Parse(Console. Read. Line()); } Console. Write. Line(total. Price); } } Global variable This program is modified by changing a declaration of total. Price from the local of Main and Super. Sum to the Global instead. Now, the variable total. Price referenced in any methods is Global total. Price (It is not a local total. Price any more. )
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 */
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.
class Program { static int total. Income = 0; static void Sale. Food() { /* be omitted */ } static void Sale. Pencil() { /* be omitted */ } public static void Main(string[] args) { string ans; do { Console. Write("Eat, Write, or Quit (E/W/Q): "); ans = Console. Read. Line(); if(ans == "E") Sale. Food(); else if(ans == "W") Sale. Pencil(); } while(ans != "Q"); Console. Write. Line("Total income = {0}", total. Income); } } Overview • We declares a global variable total. Income to keep total revenue which will be displayed at the end of the program. • We divide our work into 2 parts which are Sale. Food and Sale Pencil.
The Sale. Foof Method static void Sale. Food() { Console. Write("Omlet or Chicken Kraprao (O/C): "); string ans = Console. Read. Line(); if(ans == "O") { Console. Write. Line("The price is 10 baht. Thanks"); total. Income += 10; } else if(ans == "C") { Console. Write. Line("The price is 15 baht. Thanks"); total. Income += 15; } } This method can reference total. Income without declaration because this variable was already declared in the class as Global 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:
namespace Cons. Proc 7 Global { class Class 1 { static int x, y, z, sum, res; static void PRG 1() { sum = sum + res; All variables referenced in this method res = res % 5; are Global variables because there are Console. Write. Line("In PRG 1, sum = {0}", sum); not any variables declared in the Console. Write. Line("In PRG 1, res = {0}", res); } method itself. static void PRG 2() { int sum; A variable sum in this method is local sum = res * 2; variable whereas res is a global variable. Console. Write. Line("In PRG 2, sum = {0}", sum); } static void Main(string[] args) { x = 8 ; y = 15; z = 30; All variables referenced in this method sum = x + y + z; are Global variables because there are res = x * y; not any variables declared in the Console. Write. Line("In Main(), sum = {0}", sum); Console. Write. Line("In Main(), res = {0}", res); method itself. PRG 1(); PRG 2(); Console. Write. Line("Back to Main(), sum = {0}", sum); } } } Example 1 : an explanation is on the next slide.
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 PRG 1() : No Local variables declaration in the method itself. Therefore, all variables referenced in the method PRG 1() are Global Variables. In PRG 2() : 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.
แกะรอยคาของตวแปรแตละตวของตวอยางท พรอมทงเหตผลสนบสนน 1. At Main : () 1 Console. Write. Line("In Main(), sum = {0}", sum); value of sum is 53 Console. Write. Line("In Main(), res = {0}", res); value of res is 120 2. At PRG 1: () Console. Write. Line("In PRG 1(), sum = {0}", sum); value of sum is 173 Console. Write. Line("In PRG 1(), 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 PRG 2: () Console. Write. Line("In PRG 2(), sum = {0}", sum); ��� sum ��� 0 (This sum is Local variable of PRG 2() 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. Write. Line("Back to Main(), sum = {0}", sum); value of sum is 173 (This sum is Global variable. Its latest value occurs from the execution in PRG 1().
PRG 1() Local variable: ไมม Global variable: sum, res PRG 2() Local variable: sum Global variable: res Main() Local variable: ไมม Global variable: x, y, z, sum, res
Example 2 class Class. Globa 2 { static int op 1, op 2, answer; The variables op 1 and op 2 referenced in Main() and the static void Compute(int op 1, int op 2) { variables op 1 and op 2 int i = 1; declared in the Compute() answer = 1; are different variables even while (i <= op 2) { though theirs may duplicate. answer = op 1 * answer; i = i+1; The variables op 1 and op 2 } referenced in Main() are } // end of compute Global variable whereas op 1 static void Main(string[] args){ Console. Write. Line("Enter 2 numbers"); and op 2 in Compute() are op 1 = int. Parse(Console. Read. Line()); Local variable. op 2 = int. Parse(Console. Read. Line()); Compute(op 1, op 2); answer = answer/2; Console. Write. Line("Back to Main(), final value = {0}", answer); } }
Tracing of variables in the example 2 In 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 op 1 and op 2 are passes to the Computer()) Suppose that op 1 = 5 and op 2 = 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.
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.
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; }
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; } Let’s try • C(1100, 10( • C(40, 2(
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.
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.
Exercise • Testing the following program: class Program { static int x = 0; static void Test(int y) { x = y + 1; Console. Write. Line(x); } public static void Main(string[] args) { Console. Write. Line(x); Test(10); Console. Write. Line(x); } } What is the output of this program? output 0 11 11
Global vs Local Variable Modify the following program by inserting int x; class Program Output of the program { static int x = 0; 0 static void Test(int y) { 11 int x; 0 x = y + 1; Console. Write. Line(x); } Why the program displays public static void Main(string[] args) outputs as shown above? { Console. Write. Line(x); Test(10); The variable x, which was inserted , make x in Console. Write. Line(x); 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.
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. Read. Line()); int i = 0; while(i < n) { int a = 0; int b = 0; while(b < i) { a += b; b++; } Console. Write. Line(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.
Variable within a block (2) int n = int. Parse(Console. Read. Line()); int i = 0; while(i < n) { int a = 0; int b = 0; while(b < i) { a += b; b++; } Console. Write. Line(a); } Console. Write. Line(b); The variables, which are declared within a block, must be used in that block only. Being referenced outside the block causes a syntax error. 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.
Example do { Console. Write("Eat, write, or quit (E/W/Q): "); string ans = Console. Read. Line(); if(ans == "E") Sale. Food(); else if(ans == "W") Sale. Pencil(); } 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.
“Warning” static void Test(int a) { int x = a; int j = 0; while(x < a) { int j = x; Console. Write. Line(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.
Conclusion 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. • เราสามารถใชเมธอดในการ – ลดความซบซอนของโปรแกรม ตวแปรมขอบเขตการใชงานทเฉพาะเจาะจง ทำใหเราสามารถพจารณางานเปนสวนยอย ๆ แยกจากกนได – ลดความซำซอนของโปรแกรม ทำใหเราสามารถรวบรวมโปรแกรมทเหมอนกน หรอคลายกนมาไวทเมธอดเดยว เพอใหงายตอการแกไข
- Slides: 86