Presentation is loading. Please wait.

Presentation is loading. Please wait.

Method parameter passing, file input/output 01204111 Computer and Programming.

Similar presentations


Presentation on theme: "Method parameter passing, file input/output 01204111 Computer and Programming."— Presentation transcript:

1 Method parameter passing, file input/output 01204111 Computer and Programming

2 This is the main topic for today. Agenda Parameter passing in methods – Value parameters – Reference parameters – Output parameters Additional topic: input/output with files – However, examples in the second topics also illustrate ideas from the first

3 Value parameters

4 Review: Parameters passing by value What is the output of the program? static void M1(int a, int b) { b = a + 20; a++; } static void Main(string [] args) { int x = 10; M1(x, x + 10); Console.WriteLine(x); } static void M1(int a, int b) { b = a + 20; a++; } static void Main(string [] args) { int x = 10; M1(x, x + 10); Console.WriteLine(x); } 10 Output: Note that x is unchanged.

5 Value parameters By default, parameters passed to a method are passed by value. Values of actual parameters are copied to formal parameters. 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(); } } } 2362 actual parameters formal parameters

6 A bigger example static void Main(){... PrintBox(size);... } static void PrintChar(char c, int n){... } static void PrintBox(int s){... PrintChar('x',s-2);... } The data value of size is copied to s. 'x' is copied to c. s-2 is evaluated and the resulting value is copied to n. Parameters s, c, and n are value parameters.

7 Another example for value parameters static void Main() { string username; int birth_year; Console.Write("Input your name : "); username = Console.ReadLine(); Console.Write("What year did you born ? "); birth_year = int.Parse(Console.ReadLine()); Showinfo(username, 2010-birth_year); } static void Showinfo(string name,int age){ Console.WriteLine(“Hey {0}!!”,name); Console.WriteLine(“Your age is {0}.”,age); }

8 Changing value parameters Since only values are passed to value parameters, formal parameters and the actual parameters are not related to each other after the method call static int SumFromTo(int fr, int to) { int t = 0; while(fr <= to) { t += fr; fr++; } return t; } static void Main(string [] args) { int a = 10; Console.WriteLine( SumFromTo(a,a+10)); Console.WriteLine(a); } static int SumFromTo(int fr, int to) { int t = 0; while(fr <= to) { t += fr; fr++; } return t; } static void Main(string [] args) { int a = 10; Console.WriteLine( SumFromTo(a,a+10)); Console.WriteLine(a); } a10fr10 to20 21 SumFromTo runs, and changes the value of fr. SumFromTo runs, and changes the value of fr. Note that this has nothing to do with a Note that this has nothing to do with a

9 Value parameters This type of parameters is similar to parameter passing in Python. Value parameters are easier to reason with. – We will examples after we learn other types of parameters.

10 Limitation: example 1 You want to write a method that finds all roots of a quadratic equation: ax 2 + bx + c – There are two roots. – Problem: how can the method send the solutions back to the caller?

11 Wrong solution 1 How can the method send the solutions back to the caller? – Try to return them both. static double SolveEq(double a, double b, double c) { // do some work return sol1, sol2; } static double SolveEq(double a, double b, double c) { // do some work return sol1, sol2; } Return type must match the declaration. And we do not know data types appropriate for returning many values at the same time. Return type must match the declaration. And we do not know data types appropriate for returning many values at the same time.

12 Wrong solution 2 How can the method send the solutions back to the caller? – Use parameters static double SolveEq(double a, double b, double c, double sol1, double sol2) { // do some work sol1 = (some formula); sol2 = (some formula); } static void main() { double s1, s2; SolveEq(1, 2, 4, s1, s2); } static double SolveEq(double a, double b, double c, double sol1, double sol2) { // do some work sol1 = (some formula); sol2 = (some formula); } static void main() { double s1, s2; SolveEq(1, 2, 4, s1, s2); } Any changes in sol1 and sol2 do not have any effect to s1 and s2, because sol1 and sol2 are value parameters.

13 Bad working solution: Global variables (1) Since global variables can be accessed by both method Main and method SolveEq, you can potentially use them. But this, in general, is not a good design. class Example { static double sol1, sol2; static void SolveEq(double a, double b, double c) { // do some work sol1 = (some formula); sol2 = (some formula); } static void main() { SolveEq(1, 2, 4); Console.WriteLine("{0}, {1}", sol1, sol2); } class Example { static double sol1, sol2; static void SolveEq(double a, double b, double c) { // do some work sol1 = (some formula); sol2 = (some formula); } static void main() { SolveEq(1, 2, 4); Console.WriteLine("{0}, {1}", sol1, sol2); }

14 Bad working solution: Global variables (2) The problem with global variables is that this way of communication is usually not clear. When programs get larger, this kind of hidden relationships can cause tons of problems. class Example { static double sol1, sol2; static void SolveEq(double a, double b, double c) { // do some work sol1 = (some formula); sol2 = (some formula); } static void ComputePrice(int a, int b) { sol1 = (some formula); } static void main() { SolveEq(1, 2, 4); ComputePrice(1,5); Console.WriteLine("{0}, {1}", sol1, sol2); } class Example { static double sol1, sol2; static void SolveEq(double a, double b, double c) { // do some work sol1 = (some formula); sol2 = (some formula); } static void ComputePrice(int a, int b) { sol1 = (some formula); } static void main() { SolveEq(1, 2, 4); ComputePrice(1,5); Console.WriteLine("{0}, {1}", sol1, sol2); }

15 Limitation: example 2 Write a method that takes 3 integers and sort them. Again: – It is impossible to do so with value parameters. – It is very hard to do with return-statement. – It is not good to use global variables.

16 Reference parameters

17 Instead of passing values from actual parameters to the formal parameters, reference parameters are aliases to the actual parameters.

18 Example 1 Note the ref keyword. When Increment is called, the formal parameter x becomes a reference for a, i.e., they are the same variable. static void Increment(ref int x) { x++; Console.WriteLine(x); } static void Main() { int a = 10; Console.WriteLine(a); Increment(ref a); Console.WriteLine(a); } static void Increment(ref int x) { x++; Console.WriteLine(x); } static void Main() { int a = 10; Console.WriteLine(a); Increment(ref a); Console.WriteLine(a); } a10x 11 10 11 10 11

19 How to: reference parameters Both actual and formal parameters must start with keyword ref. An actual parameter must be a variable. (It would not make much sense otherwise.) The actual parameter must have been initialized. static void SomeMethod(ref int x, int y) { // …… } static void SomeMethod(ref int x, int y) { // …… } int k = 10; SomeMethod(ref k, 10); int k = 10; SomeMethod(ref k, 10);

20 Classic example Method Swap below swaps two integers. static void Swap(ref int a, ref int b) { temp = a; a = b; b = temp; } static void Swap(ref int a, ref int b) { temp = a; a = b; b = temp; }

21 Example: Swap What does this program do? – The first two if's ensure that a is the largest number. – The last if ensures that b is no less than c. Thus, the program sorts three numbers. static void Swap(ref int a, ref int b) { temp = a; a = b; b = temp; } static void Main() { int a = int.Parse(Console.ReadLine()); int b = int.Parse(Console.ReadLine()); int c = int.Parse(Console.ReadLine()); if(a < b) Swap(ref a, ref b); if(a < c) Swap(ref a, ref c); if(b < c) Swap(ref b, ref c); Console.WriteLine("{0} {1} {2}", a, b, c); } static void Swap(ref int a, ref int b) { temp = a; a = b; b = temp; } static void Main() { int a = int.Parse(Console.ReadLine()); int b = int.Parse(Console.ReadLine()); int c = int.Parse(Console.ReadLine()); if(a < b) Swap(ref a, ref b); if(a < c) Swap(ref a, ref c); if(b < c) Swap(ref b, ref c); Console.WriteLine("{0} {1} {2}", a, b, c); }

22 Be careful (1) You can only pass variables as reference parameters. int x = 10; Swap(ref x, ref 20); One way to see that this is not possible: you can't make 20 becomes 10, when you make an assignment in method Swap.

23 Be careful (2) You can only pass initialized variables as reference parameters.

24 Thinking Corner: Sort two integers Write a method SortTwo that takes two reference parameters a and b. The method ensures that when it returns: (1) the set of values {a,b} is the same, and (2) a is less than or equal to b. I.e., the method sorts its parameters.

25 Solution static void SortTwo(ref int a, ref int b) { if(a > b) { int temp = a; a = b; b = temp; } static void SortTwo(ref int a, ref int b) { if(a > b) { int temp = a; a = b; b = temp; } // sample usage int x = 15; int y = 10; SortTwo(ref x, ref y); Console.WriteLine("{0} {1}", x, y); // output is 10 15 // sample usage int x = 15; int y = 10; SortTwo(ref x, ref y); Console.WriteLine("{0} {1}", x, y); // output is 10 15 (Click to see)

26 Ref parameters can be very confusing Consider the following method: static void EasyOne(ref int x, ref int y) { x = y + 1; y = x + 1; } static void EasyOne(ref int x, ref int y) { x = y + 1; y = x + 1; } int x = 30; int y = 10; EasyOne(ref x, ref y); Console.WriteLine(x); int x = 30; int y = 10; EasyOne(ref x, ref y); Console.WriteLine(x); What is the output of the program? 11 What does it do? int x = 30; int y = 10; EasyOne(ref x, ref x); Console.WriteLine(x); int x = 30; int y = 10; EasyOne(ref x, ref x); Console.WriteLine(x); 12 Can you explain why?

27 Side effects (1) Consider this method. static void Count(ref int a, ref int b) { b = a + 5; while(a <= b) { Console.WriteLine(a); a++; } static void Count(ref int a, ref int b) { b = a + 5; while(a <= b) { Console.WriteLine(a); a++; } How it should work. Let b = a + 5. Keep writing a, and increasing a, until a is equal to b. It should print 5 numbers, e.g.: 10 11 12 13 14

28 Side effects (2) Consider this method. static void Count(ref int a, ref int b) { b = a + 5; while(a <= b) { Console.WriteLine(a); a++; } static void Count(ref int a, ref int b) { b = a + 5; while(a <= b) { Console.WriteLine(a); a++; } int x = 10; Count(ref x, ref x); int x = 10; Count(ref x, ref x); Calling statement: What is the output? The program loops infinitely!!

29 Side effect (3) We usually call a result of any implicit connections a side effect. E.g., – A modification of variable which is not obvious to the current context as in the previous example. – The use of global variables to return results. (That is because it is not clear when you look at the program that the results have been passed through the global variables.)

30 Side effects introduce complexities Reasoning about codes with side effects can be extremely difficult. Suggestion: – Avoid having side effect, unless you really need it. – If you can't avoid that, use it with extreme care.

31 Output parameters

32 Why do you need reference parameters? In many cases that you need reference parameters, we would like to use these parameters for returning multiple-value output. It does not quite fit.

33 Problem with reference parameters Reference parameters must be initialized before passing to the methods. Using reference parameters obscures the objective of the parameters.

34 Output parameters Instead of reference parameters, sometimes it is more appropriate to use output parameters. static void Add(int x, int y, out int sum) { sum = x + y; } static void Add(int x, int y, out int sum) { sum = x + y; } int r; Add(10, 20, out r); int r; Add(10, 20, out r);

35 Differences between ref and out parameters refout GoalFor passing values into the methods and also allowing the methods to modify the parameters. To take the output of the method Actual parameters Uninitialized variables are not allowed. Any variables are allowed. Values for formal parameters Values are passed to methods via parameters. No values are passed to methods via parameters.

36 Example Method SolveEq solves a quadratic equation and outputs two results. using System; class Program { static void SolveEq(double a, double b, double c, out double s1, out double s2) { double d = Math.Sqrt(b*b - 4*a*c); s1 = (-b + d)/(2*a); s2 = (-b - d)/(2*a); } public static void Main(string[] args) { double sol1, sol2; SolveEq(1, 0, -4, out sol1, out sol2); Console.WriteLine("Solutions are {0} and {1}", sol1, sol2); Console.ReadLine(); } }

37 File Input/Output

38 Files Variables in programs are gone when programs terminates. You can stores information you want into a file so that after your program terminates, your data is safe in the hard drive.

39 File names and paths When working with files, we refer to them with their names and paths. File name Path You can think of paths as a series of nested folders to the file.

40 Files in Sharp Dev Dealing with file names and paths is confusing for beginners. Therefore, we will work in the default folder that Sharp Dev uses, and use the Project browser in Sharp Dev to locate the files. – Project browser is in the Project tab on the left panel in Sharp Dev.

41 Writing "Hello world" to a file Working with files is very similar to working with Console. This program writes "Hello world" to a file named "test.txt". Note also that we have to add using System.IO; at the top. using System; using System.IO; namespace fileio { class Program { public static void Main(string[] args) { StreamWriter sw = new StreamWriter("test.txt"); sw.WriteLine("Hello world"); sw.Close(); } } } using System; using System.IO; namespace fileio { class Program { public static void Main(string[] args) { StreamWriter sw = new StreamWriter("test.txt"); sw.WriteLine("Hello world"); sw.Close(); } } }

42 Result, and where the file is. After running the program, you will see a new console pops up and quickly disappears. This is the correct behavior. The program creates a new file, and you can find the file at bin/Debug/test.txt – You have to click "Show all files" to see this file. – You can double click at the file name to see the content of the file. show all files

43 Working folder Note that when we refer to file "test.txt" in the previous example, we did not specify any path. – In this case, the file is created in a folder where your program runs, i.e., in folder bin/Debug, which is the default working directory for C# solutions.

44 Let's see the code! The code for creating this file contains 3 steps. The second step should look very familiar. StreamWriter sw = new StreamWriter("test.txt"); sw.WriteLine("Hello world"); sw.Close(); StreamWriter sw = new StreamWriter("test.txt"); sw.WriteLine("Hello world"); sw.Close();

45 Step 1: Create the StreamWriter object To write to a file, first, you have to create a StreamWriter object. This line creates the object associate with the file "text.txt" and assigns the object to variable sw. StreamWriter sw = new StreamWriter("test.txt"); StreamWriter sw = new StreamWriter("test.txt"); You may not quite grasp the idea of objects, but later on we will come back to this, when we consider object-oriented programing.

46 Creating StreamWriter To create a StreamWriter we use operator new, and pass the file name during the creation. Idiom: StreamWriter variablename = new StreamWriter(filename); StreamWriter variablename = new StreamWriter(filename);

47 Step 2: Write, WriteLine, etc After having an object, we can call method Write and WriteLine of that object. We can use variable (e.g., sw) in place of Console. This is similar to calling Console.Write() or Console.WriteLine(), however the result will be written to the file associated with that writer. sw.WriteLine("Hello world");

48 Step 3: Close the writer After you finish writing, you have to close the writer. sw.Close();

49 Reading files To read a file, instead of a writer, we need a reader. We can then issue method ReadLine to read strings from the file, as from the console.

50 Input Example Instead of StreamWriter, we create StreamReader. We can then use it in place of Console, to read from the associated file. using System; using System.IO; namespace fileio { class Program { public static void Main(string[] args) { StreamReader reader = new StreamReader("test.txt"); int a = int.Parse(reader.ReadLine()); int b = int.Parse(reader.ReadLine()); Console.WriteLine(a + b); Console.ReadLine(); reader.Close(); } } } using System; using System.IO; namespace fileio { class Program { public static void Main(string[] args) { StreamReader reader = new StreamReader("test.txt"); int a = int.Parse(reader.ReadLine()); int b = int.Parse(reader.ReadLine()); Console.WriteLine(a + b); Console.ReadLine(); reader.Close(); } } } Input data in file "test.txt" 8234 Output:

51 Another example This program reads input file as in the following example. using System; using System.IO; class Program { public static void Main(string[] args) { StreamReader reader = new StreamReader("input.txt"); int n = int.Parse(reader.ReadLine()); int i = 0; int total = 0; while(i < n) { int x = int.Parse(reader.ReadLine()); total += x; } Console.WriteLine(total); reader.Close(); } } using System; using System.IO; class Program { public static void Main(string[] args) { StreamReader reader = new StreamReader("input.txt"); int n = int.Parse(reader.ReadLine()); int i = 0; int total = 0; while(i < n) { int x = int.Parse(reader.ReadLine()); total += x; } Console.WriteLine(total); reader.Close(); } } 513275513275 513275513275 Input file: input.txt 18 Output

52 Final remarks

53 C# has three types of parameters: – Value parameters – Reference parameters – Output parameters You should use these types carefully to avoid unintentional effects. Using file input/output is very similar to using Console, but you have to create and close appropriate reader/writer objects.


Download ppt "Method parameter passing, file input/output 01204111 Computer and Programming."

Similar presentations


Ads by Google