Method parameter passing file inputoutput 01204111 Computer and

  • Slides: 53
Download presentation
Method parameter passing, file input/output 01204111 Computer and Programming

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

Agenda • Parameter passing in methods – Value parameters – Reference parameters – Output

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

Value parameters

Value parameters

Review: Parameters passing by value static void M 1(int a, int b) { b

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

Value parameters using System; namespace met_examples { class Program { static double Poly(double a,

Value 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; } 3 6 2 public static void Main() 2 { double k = 3; double y = Poly(2, k, k+3, 2); Console. Write. Line(y); Console. Read. Line(); } } } formal parameters actual parameters • By default, parameters passed to a method are passed by value. • Values of actual parameters are copied to formal parameters.

A bigger example static void Main(){. . . Print. Box)size(; . . . }

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

Another example for value parameters static void Main() { string username; int birth_year; Console.

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

static int Sum. From. To(int fr, int to) { int t = 0; fr

static int Sum. From. To(int fr, int to) { int t = 0; fr 21 10 while(fr <= to) to 20 { t += fr; Sum. From. To runs, fr++; and changes the } value of fr. return t; } static void Main(string [] args) { int a = 10; a 10 Console. Write. Line( Sum. From. To(a, a+10)); Console. Write. Line(a); } 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 Note that this has nothing to do with a

Value parameters • This type of parameters is similar to parameter passing in Python.

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.

Limitation: example 1 • You want to write a method that finds all roots

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?

Wrong solution 1 • How can the method send the solutions back to the

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

Wrong solution 2 • How can the method send the solutions back to the

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

Bad working solution: Global variables (1) class Example { static double sol 1, sol

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

Bad working solution: Global variables (2) class Example { static double sol 1, sol

Bad working solution: Global variables (2) class Example { static double sol 1, sol 2; static void Solve. Eq(double a, double b, double c) { // do some work sol 1 = (some formula); sol 2 = (some formula); } static void Compute. Price(int a, int b) { sol 1 = (some formula); } static void main() { Solve. Eq(1, 2, 4); Compute. Price(1, 5); Console. Write. Line("{0}, {1}", sol 1, sol 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.

Limitation: example 2 • Write a method that takes 3 integers and sort them.

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.

Reference parameters

Reference parameters

Reference parameters • Instead of passing values from actual parameters to the formal parameters,

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

Example 1 static void Increment(ref int x) { x x++; Console. Write. Line(x); }

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

How to: reference parameters • Both actual and formal parameters must start with keyword

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 Some. Method(ref int x, int y) { // …… } int k = 10; Some. Method(ref k, 10);

Classic example • Method Swap below swaps two integers. static void Swap(ref int a,

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 =

static void Swap(ref int a, ref int b) { temp = a; a = b; b = temp; } static void Main() { int a = int. Parse(Console. Read. Line()); int b = int. Parse(Console. Read. Line()); int c = int. Parse(Console. Read. Line()); 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. Write. Line("{0} {1} {2}", a, b, c); } 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.

Be careful (1) • You can only pass variables as reference parameters. int x

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.

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

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

Thinking Corner: Sort two integers • Write a method Sort. Two that takes two

Thinking Corner: Sort two integers • Write a method Sort. Two 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.

Solution static void Sort. Two(ref int a, ref int b) { if(a > b)

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

Ref parameters can be very confusing • Consider the following method: static void Easy.

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

Side effects (1) • Consider this method. static void Count(ref int a, ref int

Side effects (1) • Consider this method. static void Count(ref int a, ref int b) { b = a + 5; while(a <= b) { Console. Write. Line(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

Side effects (2) • Consider this method. static void Count(ref int a, ref int

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

Side effect (3) • We usually call a result of any implicit connections a

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

Side effects introduce complexities • Reasoning about codes with side effects can be extremely

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.

Output parameters

Output parameters

Why do you need reference parameters? • In many cases that you need reference

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.

Problem with reference parameters • Reference parameters must be initialized before passing to the

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

Output parameters • Instead of reference parameters, sometimes it is more appropriate to use

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; } int r; Add(10, 20, out r);

Differences between ref and out parameters ref out Goal For passing values into To

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

using System; class Program { static void Solve. Eq(double a, double b, double c,

using System; class Program { static void Solve. Eq(double a, double b, double c, out double s 1, out double s 2) { double d = Math. Sqrt(b*b - 4*a*c); s 1 = (-b + d)/(2*a); s 2 = (-b - d)/(2*a); } public static void Main(string[] args) { double sol 1, sol 2; Solve. Eq(1, 0, -4, out sol 1, out sol 2); Console. Write. Line("Solutions are {0} and {1}", sol 1, sol 2); Console. Read. Line(); } } Example • Method Solve. Eq solves a quadratic equation and outputs two results.

File Input/Output

File Input/Output

Files • Variables in programs are gone when programs terminates. • You can stores

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.

File names and paths • When working with files, we refer to them with

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

Files in Sharp Dev • Dealing with file names and paths is confusing for

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.

Writing "Hello world" to a file using System; using System. IO; namespace fileio {

Writing "Hello world" to a file using System; using System. IO; namespace fileio { class Program { public static void Main(string[] args) { Stream. Writer sw = new Stream. Writer("test. txt"); sw. Write. Line("Hello world"); sw. Close(); } } } • 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.

Result, and where the file is. show all files • After running the program,

Result, and where the file is. show all files • 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.

Working folder • Note that when we refer to file "test. txt" in the

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.

Let's see the code! Stream. Writer sw = new Stream. Writer("test. txt"); sw. Write.

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

Step 1: Create the Stream. Writer object • To write to a file, first,

Step 1: Create the Stream. Writer object • To write to a file, first, you have to create a Stream. Writer object. • This line creates the object associate with the file "text. txt" and assigns the object to variable sw. Stream. Writer sw = new Stream. Writer("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.

Creating Stream. Writer • To create a Stream. Writer we use operator new, and

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

Step 2: Write, Write. Line, etc • After having an object, we can call

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

Step 3: Close the writer • After you finish writing, you have to close

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

Reading files • To read a file, instead of a writer, we need a

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

Input Example using System; using System. IO; namespace fileio { class Program { public

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

using System; using System. IO; class Program { public static void Main(string[] args) {

using System; using System. IO; class Program { public static void Main(string[] args) { Stream. Reader reader = new Stream. Reader("input. txt"); int n = int. Parse(reader. Read. Line()); int i = 0; int total = 0; while(i < n) { int x = int. Parse(reader. Read. Line()); total += x; } Console. Write. Line(total); reader. Close(); } } Another example • This program reads input file as in the following example. Input file: input. txt 5 1 3 2 7 5 Output 18

Final remarks

Final remarks

Final remarks • C# has three types of parameters: – Value parameters – Reference

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