Upload
lisa-eaton
View
219
Download
0
Embed Size (px)
DESCRIPTION
Major Topics Methods Input Output Global vs. Local Scope of variables Array Declare, Create, Initialize, Access Run ‘for’ loop with array Array with methods 1D vs. 2D vs. multiD
Citation preview
Final ReviewAuthor: Thanachat ThanomkulabutEdited by Supaporn Erjongmanee
Final Review22 September 2011
Outline2
Major topics Methods Arrays structs
Major Topics Methods
Input Output Global vs. Local Scope of variables
Array Declare, Create, Initialize, Access Run ‘for’ loop with array Array with methods 1D vs. 2D vs. multiD
Major Topics (cont.)
struct Define, Create, Access Array of struct struct with methods
File I/O Collection
Pre-midterm Topics Data types & Variable declaration Math expression Logical expression
How to write condition If switch-case Loop
while, do…while, for break, continue
Outline6
Major topics Methods Arrays structs
Methods7
Input Output Global vs. Local Scope of variables
8
NamespaceClass
Main()
Method1()
Method2()
Method3()
MethodN()
C# Structure – Multiple Methods
9
Characteristics of Method
Method
Type of Method (Output)
No Returned
valueReturned
value
Parameter Passing (Input)
No Parameter
Pass by value
Pass by reference
ref out
Define Method
static <return-type> <method-name>(<parameter list>){ <const/variable declaration>; <statements>;}
10
Syntax
When see a method, answer the followings:
1. What is method name?2. Are there any input? If so, for each input:
a) what’s data type?b) What’s variable name?c) Is it regular or ‘ref’ or ‘out’?
3. Are there any output? If so, for each output:a) what’s data type?b) What’s variable name to store output?
12
Method Input Input
Name of copied variable can be different from original variable
Data type of copied and original variables must be the same!
static void Subject (double num, bool okay, int unit){ ... ... ...}static void Main() { double n; int limit; bool found; ... ... Subject(12.7, true, (limit*3)+5); ... ...}
Method Input (cont.) Input (cont.)
We must choose input to be Pass by Value or Pass by Reference
Pass by Value Data type + Variable name
Pass by Reference => Value returns automatically. Do not use “return”.
ref + Data type + Variable name Must initialize value of Variable before calling the
methodstatic void sub(int a, ref int b){ b = a - b;}
Define Method
static <return-type> <method-name>(<parameter list>){ <const/variable declaration>; <statements>;}
• return-type can be• void = return no value• int, double, string, … = return value with specified data
type and need return statement inside method 14
14
Syntax
Method Output Output
We must choose input to be Returned Value or Pass by Reference Returned Value: appear before Method name
static returned_data_type Method_name (input_parameter_list) { … } Need “return” as one statement in a method
Pass by Reference: appear in (..) after Method name Value returns automatically. Do not use “return”. ref + Data type + Variable name
Must initialize value of Variable before calling the method out + Data type + Variable name
No need to initialize value of Variable before calling the method Value of variable before calling the method will not be passed into the
method
static void add(int a, ref int b, out int c) { c = a + b;}
static int add(int a, int b) { return a + b;}
Pass by Value
16
Change in copied variable in the method has no effect on the original variable
static void Square(int num){ num = num*num; Console.WriteLine("num = {0}",num);}
static void Main(){ int num=5; Square(num); Console.WriteLine(“num = {0}",num); }
5num
num525
num = 25num = 5
Monitor
Pass by reference17
static void Main(){ int a, b, c; a = 2; b = 3; c = 4; Hello(a, ref b, out c);
Console.WriteLine(“Finally a = {0}, b = {1}, c = {2}”,a,b,c);}
static void Hello (int x, ref int y, out int z){ x = 2*x; y = 2*y; z = x+y; Console.WriteLine(“Hello x = {0}, y = {1}, z = {2}”, x,y,z);}
a2
b3
c4
x
2
y
3
z104 6
10
Hello x = 4, y = 6, z = 10Finally a = 2, b= 6, c = 10
6
Monitor
“Out” does not pass in any
value to method
Examples
18
static void Main() { PrintLine(‘n’, 14);
double width = 5, height = 10; double area = Area(width, height); Console.WriteLine(area); Console.WriteLine(compAve(10,20,30));}
static void PrintLine(char a, int b ) { Console.WriteLine(“{0} is {1}th alphabet”, a, b);}
static double Area(double w, double h) { return w*h;}
static double compAve(int x1, int x2, int x3) { return (x1+x2+x3)/3;}
n is 14th alphabet5020
Monitor
Examples 2
19
static void Main() { char x = ‘p’, y = ‘q’; int p = 3, q = 5; double a=5, b=10, c=0, d, e; sub( p, q, out d); mult( a , b, ref c); switch( ref x, ref y);}
static void sub(int a, int b, out double c) { c = a – b ;}
static void mult(double p, double q, ref double r) { r = p * q;}
static void switch(ref char x1, ref char x2) { char temp = x1; x1 = x2; x2 = temp;}
Methods: Passing outputstatic void Main() { int x = 1, y = 2; Add100_v1(x,y); Console.WriteLine(“{0},{1}”,x,y); Add100_v2(ref x,ref y); Console.WriteLine(“{0},{1}”,x,y); Add100_v3(ref x,y); Console.WriteLine(“{0},{1}”,x,y)}static void Add100_v1(int num, int num2) { num += 100; num2 += 100;}static void Add100_v2(ref int num, ref int num2) { num += 100; num2 += 100;}static void Add100_v3(ref int num, int num2) { num += 100; num2 += 100;}
1,2101,102201,102
Monitor
Methods with ref ref can do:1) pass values into
method2) return the changed
values back
Variables passing with ref need to be initialized before passing.
ref can be used with regular or out
static void Main() { int x = 1, y = 2; int result1; Add_v1(x,y,out result1); Console.WriteLine(result1); int result2; Add_v2(x,y,ref result2); Console.WriteLine(result2);}static void Add_v1(int num, int num2, out num3) { num3 = num + num2;}static void Add_v2(int num, int num2, ref num4) { num4 = num + num2;}
Methods with out • Out can do:• pass the changed values
back.
Variables passing with out DO NOT need to be initialized before passing.
No Initialized value for result1 (using out)
OK!
No initialized value for result2 (using ref)
ERROR!!!!
static void Main() { int x = 1, y = 2; int result1; Add_v1(x,y,out result1); Console.WriteLine(result1); int result2 = 0; Add_v2(result1,y,ref result2); Console.WriteLine(result2);}static void Add_v1(int num, int num2, out num3) { num3 = num + num2;}static void Add_v2(int num, int num2, ref num4) { num4 = num + num2;}
35
Monitor
Methods with out • Out can do:• pass the changed values
back.
Variables passing with out DO NOT need to be initialized before passing.
No Initialized value for result1 (using out)
OK!
Initialized value for result2 (using ref)
OK!
Global vs. Local Variables23
Global variables, constants, structs
namespace
class
Main()
MethodX()
Local variables, constants, statements
Local variables, constants, statements
Global vs. Local Variables (cont.)
24class
Main() Method1()
x y
n
int x;
static int n;
x = 5;y = 12;n = 9;
int y;x = 5;y = 12;n = 9;
Variable Scope: Example #1using System;class ScopeTest { static void Main() { for(int i=0;i<5;i++){ Console.Write(“*”); } Console.Write(i); }}
Scope of this
i starts hereThen ends
here
This line is not in i's
scope
25
Variable Scope: Example #2using System;class ScopeTest { static void Main() { int x; x = 5; }
static void Method1() { Console.WriteLine(x); }}
Scope of this x starts here
Then ends here
This line is not in x's
scope
26
Example 127
class Test { static void Main() { int x = 3; Add10(x); Console.WriteLine(x); } static void Add10(int x){ x += 10;
}}
3Monitor
Method Add10 will not pass new value of ‘x’ back since ‘x’ is not
passed by reference.
Program will show value of variable “x” in
Method Main
Example 128
class Test { static int sum = 0; static void Main() { Console.Write(“sum={0}”,sum); Add(2); Console.Write(“sum={0}”,sum); } static void Add(int y){ sum += y; }}
sum=0Monitor
sum=2
Example 2
Example 129
class Test { static int sum = 0; static void Main() { Console.Write(“sum={0}”,sum); Add(2); Console.Write(“sum={0}”,sum); } static void Add(int y){ sum += y; }}
sum=0Monitor
sum=2
Console.Write(“y={0}”,y);
Error
Example 2
Example 3
30 class Test { static int sum = 0; static void Main() { Console.WriteLine(sum); methodA(); Console.WriteLine(sum); } static void methodA(){ int sum = 5; Console.WriteLine(sum); }}
In Main, value of GLOBAL variable ‘sum’ is used.
In methodA, value of LOCAL variable ‘sum’ is
used.
0Monitor 5
0Does this program work?
Outline31
Major topics Methods Arrays structs
Arrays
Declare, Create, Initialize, Access Run ‘for’ loop with array Array with methods 1D vs. 2D vs. multiD
Array: 1D• Declare array
– int [] arr;• Create array: Must have size
– arr = new int [5];• Declare + create: Must have size
– int [] arr = new int [5];• If we want to initialize, we need to
declare (+create) array first. No need to have size– int [] arr = new int [] {5,6,7,8,9};– int [] arr ={5,6,7,8,9};
Array: 1D34
Which ones are valid C# statements ?1. int [] arrayA = new int[] {3, 6, 9};2. int arrayA = new int[3] {3, 6, 9}; 3. int [] arrayA = new int {3, 6, 9};4. int arrayA = new int {3, 6, 9};5. int [] arrayA = new int[3] ;6. int [] arrayA = new int[] ;7. int [] arrayA = new int[3] {3, 6, 9};
Array: 1D (cont.)• Accessing array: index = integer
– Use index: 0,1,…,size-1• Accessing 1 element in array: arr[index]
– Example: arr[0] = 10;• Accessing many elements in array: ‘for’
– for (int i = 0; i < arr.Length; i++) arr[i] = i+10;
• Only-Read all elements in array– foreach (int x in arr)
Console.WriteLine(x);
Array: 1D (cont.)
• Only-Read all elements in array (cont.)– Assume arr2 is array with double typeint count = 0;foreach (double y in arr2) { if (y > 0) count++;}
String37
String is “array of chars.”string name = “Bossa”;Console.WriteLine(name[0]);Console.WriteLine(name[4-3]);name[4] = ‘m’;
‘B’
‘o’ ‘s’nam
e
0 1 2‘s’3
‘a'
4 BOutput
o
Each element in string is for “reading
only”
Array: 2D• Declare array
– int [,] arr;• Create array: Must have size
– arr = new int [3,2];• Declare + create: Must have size
– int [,] arr = new int [3,2];• If we want to initialize, we need to
declare (+create) array first. No need to have size– int [,] arr = new int [,] {{5,6},{7,8},
{9,0}};– int [,] arr ={{5,6},{7,8},{9,0}};
Array: 2D • Accessing array: 2 indices
– Use row index: 0,1,…,row_size-1– Use column index: 0,1,…,col_size-1
• Accessing 1 element in 2D array: arr[row_index, col_index]– Example: arr[0,1] = 5;
• Get size:– arr.GetLength(0): Number of rows– arr.GetLength(1): Number of columns– arr.Length: Number of total elements
Array: 2D (cont.)
• Accessing all elements in 2D array– Use 2 ‘for’ loops: go through all rows and
all columns– Different index for each ‘for’ loop– for (int i = 0; i < arr.GetLength(0); i++)
for (int j = 0; j < arr.GetLength(1); j++)arr[i,j] = i*10+j;
Array: 2D (cont.)
• Accessing one row (e.g., 3rd row) in 2D array– Use 1 ‘for’ loops to go through all
columns– Fixed row index for given row– ‘i’ index for column– Example: for (int i = 0; i < arr.GetLength(1); i++)
Console.WriteLine(arr[2 , i]);
Array: 2D (cont.)
42
• Accessing one column (e.g., 2nd column) in 2D array– Use 1 ‘for’ loops to go through all rows– Fixed column index for given column– ‘i’ index for row– for (int i = 0; i < arr.GetLength(0); i++)
Console.WriteLine(arr[ i, 1]);
static void Main() { int [] arr = new int [10]; Arr_initial(arr); Display_arr(arr); Add10(arr); Display_arr(arr);}static void Arr_initial (int [] a) { for (int i = 0; i < a.Length; i++) a[i] = i;}static void Add10(int [] a) { for (int i = 0; i < a.Length; i++) a[i] = a[i]+10;}static void Display_arr(int [] a) { for (int i = 0; i < a.Length; i++) Console.Write(“{0},” a[i]); Console.WriteLine();}
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,
Monitor
Pass array into method without ‘ref’1) Pass the changed values back.2) Can’t pass the new array back
Methods: passing array with no ref
Array is initialized all elements with 0 automatically.
Print out values from first to last elements in array
static void Main() { int [] arr = new int [10]; Arr_initial(arr); Display_arr(arr); Op_arr(arr); Display_arr(arr);}static void Arr_initial (int [] a) { for (int i = 0; i < a.Length; i++) a[i] = i;}static void Op_arr(int [] a) {
a = new int [5];}static void Display_arr(int [] a) { for (int i = 0; i < a.Length; i++) Console.Write(“{0},” a[i]); Console.WriteLine();}
0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,
Monitor
Pass array into method without ‘ref’1) Pass the changed values back.2) Can’t pass the new array back
Methods: passing array with no ref
Without ref: new array will not be passed back to Main
Declare new array with 5 elements
static void Main() { int [] arr = new int [10]; Arr_initial(arr); Display_arr(arr); Op_arr(arr); Display_arr(arr);}static void Arr_initial (int [] a) { for (int i = 0; i < a.Length; i++) a[i] = i;}static void Op_arr(int [] a) {
a[0]=100; a = new int [5]; a[1]=1000;}static void Display_arr(int [] a) { for (int i = 0; i < a.Length; i++) Console.Write(“{0},” a[i]); Console.WriteLine();}
0,1,2,3,4,5,6,7,8,9,100,1,2,3,4,5,6,7,8,9,
Monitor
Pass array into method without ‘ref’1) Pass the changed values back.2) Can’t pass the new array back
Methods: passing array with no ref
Without ref: changed values after new array will not be passed back to Main
Declare new array with 5 elements
static void Main() { int [] arr = new int [10]; Arr_initial(arr); Display_arr(arr); Op_arr(ref arr); Display_arr(arr);}
static void Arr_initial (int [] a) { for (int i = 0; i < a.Length; i++) a[i] = i;}static void Op_arr(ref int [] a) {
a = new int [5];}static void Display_arr(int [] a) { for (int i = 0; i < a.Length; i++) Console.Write(“{0},” a[i]); Console.WriteLine();}
0,1,2,3,4,5,6,7,8,9,0,0,0,0,0,
Monitor
Methods: passing array with ref Pass array into method with ‘ref’
1) Pass the changed values back.2) Can pass the new array back
Declare new array with 5 elements
With ref: new array will be passed back to Main
static void Main() { int [] arr = new int [10]; Arr_initial(arr); Display_arr(arr); Op_arr(ref arr); Display_arr(arr);}static void Arr_initial (int [] a) { for (int i = 0; i < a.Length; i++) a[i] = i;}static void Op_arr(ref int [] a) { a[0] = 100;
a = new int [5];a[2]=1000;
}static void Display_arr(int [] a) { for (int i = 0; i < a.Length; i++) Console.Write(“{0},” a[i]); Console.WriteLine();}
0,1,2,3,4,5,6,7,8,9,0,0,1000,0,0,
Monitor
Methods: passing array with ref Pass array into method with ‘ref’
1) Pass the changed values back.2) Can pass the new array back
Declare new array with 5 elements
With ref: changed values after new array will be passed back to Main
Outline48
Major topics Methods Arrays structs
struct
Define, Create, Access Array of struct struct with methods
Define struct
StudentInfo
Name: Paul
Dept: Math
Age: 18
Gender: M
string
string
int
char
struct StudentInfo { public string name; public string dept; public int age; public char gender;}
Must use "struct" keyword
Every struct needs a name
Protection level – for now always use "public”
Members of struct
50
using System;class StructTest {
static void Main() { }}
Create struct: Format I & II
struct_name var_name;
StudentInfo
Name:
Dept:
Age:
Gender:
string
string
int
charStdInfo student
= new StdInfo ();StdInfo student;
struct StdInfo { public string name; public string dept; public int age; public char gender;}
51
struct_name var_name = new struct_name ();
Syntax
student.name = “Paul”;
Console.WriteLine(student.name);52
Access struct
var_name.member_name
PaulMonitor
Name:
Dept:
Age:
Gender:
string
string
int
char
• Assign value
• Display value
Paul StdInfo student;
52
Declare & Create Array of struct
Declare Array
Declare Array of struct
double[] score;score = new double[4];
StdInfo[] student;student = new StdInfo[4];
score0 1 2 3
idnamedept
idnamedept
idnamedept
idnamedept
0 1 2 3
student
struct StdInfo { public int id; public string name; public string dept;}
53
Access Array of struct
Access Array
Access Array of structscore[2] = 5;
student[0].name = ”Paul";
idnamedept
idnamedept
idnamedept
idnamedept
0 1 2 3student
score0 1 2 3
5
student[3].id = 713;
713Paul
54 var_name[index].struct_member
Example : Read 1 Student’s Informationclass StructTest { struct StdInfo { public int id; public string name; public string dept; } static void Main() {
}}
StdInfo student; Console.Write("Input ID: ");student.id = int.Parse(Console.ReadLine());Console.Write("Input Name: ");student.name = Console.ReadLine();Console.Write("Input Dept: ");student.dept = Console.ReadLine();
55
1 student
StdInfo
ID:
Name:
Dept:
int
string
string
Example : Read 50 Students’ Informationclass StructTest { struct StdInfo { public int id; public string name; public string dept; } static void Main() {
}}
StdInfo student; Console.Write("Input ID: ");student.id = int.Parse(Console.ReadLine());Console.Write("Input Name: ");student.name = Console.ReadLine();Console.Write("Input Dept: ");student.dept = Console.ReadLine();
56
StdInfo[] student = new StdInfo[50];for(int i=0;i<50;i++){ Console.Write("Input ID: "); student[i].id = int.Parse(Console.ReadLine()); Console.Write("Input ์Name: "); student[i].name = Console.ReadLine(); Console.Write("Input Dept: "); student[i].dept = Console.ReadLine();}
StdInfo
ID:
Name:
Dept:
int
string
string
50 students
Example: Display names of Math students
Display names of students from Math department
for(int i=0;i<50;i++){
if(student[i].dept == ”Math") Console.WriteLine(student[i].name);
}
idnamedept
601 idnamedept
623…
idnamedept
PamMath
0 1 49student
713BobPaul
Math English
57
57
Methods: passing with structstruct complex_num {
public double real; public double imag; }static void Main() { complex_num num1, num2; assign_complex(5,2,out num1); assign_complex(1,7,out num2); display_complex(num1); add_complex(ref num1, num2); display_complex(num1);}static void assign_complex(double r, double im, out complex_num n) { n.real = r; n.imag = im; }static void add_complex(ref complex_num n, complex_num n2) { n.real = n.real + n2.real; n.imag = n.imag + n2.imag; }static void display_complex(complex_num n) { Console.WriteLine(“{0}+{1}i”,n.real, n.imag); }
5+2i6+9i
Monitor
Similar to regular variables, we can use struct to pass by value or pass by reference (ref or out).Replace data type with struct name
Good Luck