Struct Data Type Computers and Programming (01204111)

Slides:



Advertisements
Similar presentations
Exposure C++ Chapter XVI C++ Data Structures, the Record.
Advertisements

Structures in C.
START DEFINITIONS values (3) N1 = (8, 1,-9) i N1 average N3,2 sum N2 = 0 temp N1 Do not guess or assume any values! Follow the values of the variables.
Arrays. Topics Tables of Data Arrays – Single Dimensional Parsing a String into Multiple Tokens Arrays - Multi-dimensional.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
1 More on Arrays Passing arrays to or from methods Arrays of objects Command line arguments Variable length parameter lists Two dimensional arrays Reading.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
Structures COMP104 Structs / Slide 2 Motivation: a new type * Structures hold data that belong together. * Examples: n Student record  student id, name,
Chapter 7 & 8- Arrays and Strings
Chapter 11 Structure. 2 Objectives You should be able to describe: Structures Arrays of Structures Structures as Function Arguments Dynamic Structure.
Chapter 7: Arrays. Outline Array Definition Access Array Array Initialization Array Processing 2D Array.
Chapter 11: Structured Data. Slide Introduction An array makes it possible to access a list or table of data of the same data type by using a single.
Java Unit 9: Arrays Declaring and Processing Arrays.
03/16/ What is an Array?... An array is an object that stores list of items. Each slot of an array holds an individual element. Characteristics.
VARIABLES, TYPES, INPUT/OUTPUT, ASSIGNMENT OPERATION Shieu-Hong Lin MATH/CS Department Chapel.
Structs. Structures We already know that arrays are many variables of the same type grouped together under the same name. Structures are like arrays except.
Foundation Studies Course M.Montebello Records Foundation Studies Course.
1 Structures. Structure (struct) Definition A Structure is a container, it can hold a bunch of things. –These things can be of any type. Structures are.
1 Conditional statements Dept. of Computer Engineering Faculty of Engineering, Kasetsart University Bangkok, Thailand.
1 DATA STRUCTURES: LISTS. 2 LISTS ARE USED TO WORK WITH A GROUP OF VALUES IN AN ORGANIZED MANNER. A SERIES OF MEMORY LOCATIONS CAN BE DIRECTLY REFERENCED.
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
The basics of the array data structure. Storing information Computer programs (and humans) cannot operate without information. Example: The array data.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
ARRAYS Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall
Classes and Object-Oriented Programming in C# Computers and Programming ( )
Review of ICS 102. Lecture Objectives To review the major topics covered in ICS 102 course Refresh the memory and get ready for the new adventure of ICS.
Session 08 Module 14: Generics and Iterator Module 15: Anonymous & partial class & Nullable type.
STRUCT Thanachat Thanomkulabut 1. Array Review 2  Group multiple items of the same type into one "variable" double[] score; score = new.
Spring 2005, Gülcihan Özdemir Dağ Lecture 7, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 7 Outline 7. 1.
Structures in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR.
1 Structures UniMAP SEM I - 11/12EKT 120 Computer Programming.
1 Advanced Issues on Classes Part 3 Reference variables (Tapestry pp.581, Horton 176 – 178) Const-reference variables (Horton 176 – 178) object sharing:
1 st Semester Module2 Basic C# Concept อภิรักษ์ จันทร์สร้าง Aphirak Jansang Computer Engineering.
Methods We write methods in our programs for many reasons:
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
+ Structures and Unions. + Introduction We have seen that arrays can be used to represent a group of data items that belong to the same type, such as.
CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi.
Section 3 - Arrays and Methods. Arrays Array: collection of group of data variables of same type, sharing the same name for convenience - Easy to search.
Chapter 7: Arrays. Outline Array Definition Access Array Array Initialization Array Processing 2D Array.
11/5/2016CS150 Introduction to Computer Science 1 Announcements  Assignment 6 due on Wednesday, December 3, 2003  Final Exam on Tuesday, December 9,
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
1 Chapter 12 Arrays. 2 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating.
Structures. Outline Introduction Structure Definitions and declarations Initializing Structures Operations on Structures members Structures as Functions.
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Arrays.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Struct COMP104 Struct / Slide 2 Motivation * Structures hold data that belong together. * Examples: n Student record  student id, name, major, gender,
Final Review Author: Thanachat Thanomkulabut Edited by Supaporn Erjongmanee Final Review 22 September 2011.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
Enum,Structure and Nullable Types Ashima Wadhwa. Enumerations, Enumerations, or enums, are used to group named constants similar to how they are used.
1 st Semester Module11 Struct Type in C# Thanawin Rakthanmanon Create by: Aphirak Jansang Computer Engineering Department.
1 11/30/05CS150 Introduction to Computer Science 1 Structs.
C++ Array 1. C++ provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used.
STRUCTURES. INTRODUCTION A structure is same as that of records. It stores related information about an entity. Structure is basically a user defined.
13/10/2016CS150 Introduction to Computer Science 1 Multidimensional Arrays  Arrays can have more than one column  Two dimensional arrays have two columns.
1 st Semester Module2 Basic C# Concept อภิรักษ์ จันทร์สร้าง Aphirak Jansang Computer Engineering.
Lecture 10: Structures. Outline Introduction Structure Definitions and declarations Initializing Structures Operations on Structures members Structures.
KUKUM-06/07 EKT120: Computer Programming 1 Week 6 Arrays-Part 1.
C++ for Engineers and Scientists Second Edition Chapter 12 Pointers.
C# Basic Syntax, Visual Studio, Console Input / Output
C# Basic Syntax, Visual Studio, Console Input / Output
Test 2 Review Outline.
Lecture 9 Structure 1. Concepts of structure Pointers of structures
Structures A Structure is a collection of related data items, possibly of different types. A structure type in C++ is called struct. A struct is heterogeneous.
Command Line Arguments
Thanachat Thanomkulabut
Programming Structures.
Programming Structures.
Presentation transcript:

Struct Data Type Computers and Programming ( )

2 Outline Array revisited Data encapsulation in C# Struct Data Type   Struct Definition   Struct variable declaration   Struct variable reference   Array of struct

3 Arrays Revisited Group multiple items of the same type into one "variable" or "object" Make programming easier to manage What if we want to keep a few things that are of different types together? a1=3 a2=10 a0=7 a5=17 : Array a

4 Example Imagine that you have to write a program  To store 100 students' names  That's simple; just use an array ...and their scores  Also simple; create another array ...and also their ID, department, faculty, advisor, etc using System; class Scoring { public static void Main() { string [] name = new string[100]; double [] score = new double[100]; : } using System; class Scoring { public static void Main() { string [] name = new string[100]; double [] score = new double[100]; : }

5 More Example From the previous slide:   We want to store students' ID, name, score, department, faculty, advisor, etc   We could write a program like this: using System; class Scoring { public static void Main() { string [] name = new string[100]; int [] ID = new int[100]; double [] score = new double[100]; string [] dept = new string[100]; string [] faculty = new string[100]; string [] advisor = new string[100]; : } using System; class Scoring { public static void Main() { string [] name = new string[100]; int [] ID = new int[100]; double [] score = new double[100]; string [] dept = new string[100]; string [] faculty = new string[100]; string [] advisor = new string[100]; : } What a mess...

6 Data Encapsulation A mechanism that bundles multiple items of varying types into one item or "object" Dept="ME" Advisor="Arthur" Name="Paula" ID= Paula ME Arthur ID: Name: Dept: Advisor: Object studentInfo C# provides two kinds of data encapsulation: C# provides two kinds of data encapsulation: struct and class struct and class This course will focus on struct only. This course will focus on struct only.

7 Struct DataType Struct (record) is a structure data type. Like an array, a struct is a correction of related data items. Unlike an array, however, the individual components of a struct can contain data of different types. We can use a struct to store a variety of information about a person, such as name, marital status, age and date of birth. Each data item is stored in a separate field. We can reference each data item stored in a struct through its field name.

8 Example of Struct IDStudNameGenderDeptGPAStatus E9001PeerawatMCPE2.970 ………………… ………………… Field An internal structure of struct consists of fields, or sub struct (nested types). Each data item is stored in a separate field. We can reference each data item stored in a struct through its field name.

9 Using a struct data type Struct Definition Struct Definition Struct variable declaration Struct variable declaration struct variable reference struct variable reference

10 Struct Definition Struct Name and its structure must be defined first. We can place declaration of struct in 2 positions: 1.Between namespace and class (line 4 – 8) 2.Within a class. (line 11 – 15) using System; namespace StructName { public struct L1 { ; } class SampleStruct { public struct L2 { …………… ; } public static void Main(string[] args) { ……… ; }

11 Format of struct Definition struct StdInfo { public string ID; public string Name; public double GPA; } struct struct_name /* the reserved word public here can be omitted */ { public datatype field1; public datatype field2; ………; } Example 1 : Struct Definition The data structure named StdInfo to store a record of one student whose details consist ID, Name, and GPA

12 struct Carstruct { public string Car_Id; public string Car_Name; public bool Imported; } Example 2 : Struct Definition The data structure named Carstruct to store a record of a car whose details consist of Car_Id, Car_Name, and Imported (whether it is imported?)

13 struct LINE { public double X1; public double Y1; public double Z1; public double X2; public double Y2; public double Z2; } Example 4 : Struct Definition The data structure named LINE to store record of an order pairs of a starting point (X1, Y1, Z1) and an ending point (X2, Y2, Z2) of straight line. struct POINT { public double X; public double Y; public double Z; } Example 3 : Struct Definition The data structure named POINT to store record of a point of 3 dimensional axes (X, Y, Z)

14 struct POINT { public double X; public double Y; public double Z; } Example 5 : Struct Definition We can define a data structure LINE which consists of POINT as a sub-structure to store a starting point and an ending point of straight line. struct LINE { public POINT P1; // a starting point of straight line public POINT P2; // an ending point of straight line }

15 Struct variable declaration After being defined, struct has not been ready to be used yet. We must declare a variable whose data type is struct by using the following format: struct_name variable name; struct_name variable name = new struct_name(); OR

16 Example 1 : Struct variable declaration using System; namespace SampleStruct { class Program { struct StdInfo { public string ID; public string Name; public double GPA; } public static void Main(string[] args) { StdInfo STUDENT1; STUDENT1.ID = Console.ReadLine(); STUDENT1.Name = Console.ReadLine(); STUDENT1.GPA = double.Parse(Console.ReadLine()); …………..…. ; ……………… ; } StdInfo STUDENT1 = new StdInfo(); Or

17 using System; namespace samplestruct2 { public struct person { string ID; double salary; } class Program { public static void Main(string[] args) { person a; a.ID = Console.ReadLine(); a.salary = double.Parse(Console.ReadLine()); Console.WriteLine(a.ID); Console.WriteLine(a.salary); Console.ReadLine(); }

18 Example 2 : Struct variable declaration using System; namespace SampleStructLine { class Program { struct POINT { public double X; public double Y; } struct LINE { public POINT P1; public POINT P2; } public static void Main(string[] args) { LINE L1; L1.P1.X = -5; L1.P1.Y = -3; L1.P2.X = 4; L1.P2.Y = 3; Console.WriteLine(L1.P1.X); ……………….. ; } } } This example is to define a structure LINE which consists of sub-structure POINT to store a starting point and an ending point of a straight line on 2 dimension axes (x, y). LINE L1 = new LINE();

19 struct variable reference After a structure data type was defined and a struct variable was created, we can reference the variable by the following format : Variable.field class Program { struct StdInfo { public string ID; public string Name; public double GPA; } public static void Main(string[] args) { StdInfo STUDENT1; STUDENT1.ID = Console.ReadLine(); STUDENT1.Name = Console.ReadLine(); STUDENT1.GPA = double.Parse(Console.ReadLine()); ………………………. ; } variable declaration

20 Example 1: struct variable reference This example is to define and declare a structure to store information of one employee. class Cons_Struct1 { public struct Employee { public string ID; public string Name; public double Salary; public char Gender; public bool Status; } static void Main(string[] args) { Employee a; a.ID = Console.ReadLine(); a.Name = Console.ReadLine(); a.Salary = double.Parse(Console.ReadLine()); a.Gender = char.Parse(Console.ReadLine()); a.Status = bool.Parse(Console.ReadLine()); Console.WriteLine(a.ID); Console.WriteLine(a.Name); Console.WriteLine(a.Salary); Console.WriteLine(a.Status); }

21 From the previous example: static void Main(string[] args) { Employee a; a.ID = Console.ReadLine(); a.Name = Console.ReadLine(); a.Salary = double.Parse(Console.ReadLine()); a.Gender = char.Parse(Console.ReadLine()); a.Status = bool.Parse(Console.ReadLine()); Console.WriteLine(a.ID); Console.WriteLine(a.Name); Console.WriteLine(a.Salary); Console.WriteLine(a.Status); } E9001Yuen67,890MTrue a.IDa.Namea.Salarya.Gendera.Status The field names describe the nature of information represented. The content of each field determine the appropriate data type. For example, the employee’s name should be stored in a string field.

22 Example 2: struct variable reference This example is to define and declare a structure to store information of one employee and show some conditions. class Class1 { public struct Employee { public string ID; public string Name; public int Salary; public char Gender; public bool Status; public double Insurance; } static void Main(string[] args) { Employee a; a.ID = Console.ReadLine(); a.Name = Console.ReadLine(); a.Salary = int.Parse(Console.ReadLine()); a.Gender = char.Parse(Console.ReadLine()); a.Status = bool.Parse(Console.ReadLine()); if ((a.Salary <= 10000) && (a.Gender == 'F')) a.Insurance = a.salary * 0.5; else a.Insurance = a.salary * 0.2; Console.WriteLine(a.ID); Console.WriteLine(a.Name); Console.WriteLine(a.Salary); Console.WriteLine(a.Status); Console.WriteLine(a.Insurance); }

23 Example 3: struct variable reference This example is to find the distance between 2 points (from Pythagoras equation) P1 and P2. class PythaClass { public struct point { public double x; public double y; public double z; } public static void Main(string[] args) { point P1 = new point(); point P2 = new point(); P1.x = 1; P1.y = 5; P1.z = 9; P2.x = 2; P2.y = -9; P2.z = 8; double dx = P1.x - P2.x; double dy = P1.y - P2.y; double dz = P1.z - P2.z; double length = Math.Sqrt((dx*dx)+(dy*dy)+(dz*dz)); Console.WriteLine(length); }

24 Assigning a to b is equivalent to assigning the value of each field of a to those of b. b.ID = a.ID; b.Name = a.Name; b.Salary = a.Salary; b.Gender = a.Gender; b.Status = a.Status; b.Insurance = a.Insurance; *** Struct variable can be directly assigned to the other. *** static void Main(string[] args) { Employee a, b; ………………………… ; ………………………… ; // Reading values to various fields of struct a ………………………… ; b = a; // Values of struct variable a can be directly assigned to b. }

25 Array of struct From the previous examples, a structure was created to store only one record. Example : The structure shown below was created to store information of one employee only. class Cons_Struct1 { public struct Employee { public string ID; public string Name; public double Salary; public char Gender; public bool Status; } static void Main(string[] args) { Employee a; …………. ; } However, if we want to store information of more than one employees, we need to create an array of struct.

26 Example of an array structure of struct IDNameGenderDeptGPA 1E9001PeerawatMCPE2.97 2E9002PanitaFEE3.78 3E9003LuxanaFCPE2.75 The structure shown above is an array of struct. It was created to store information (Identification number, Name, Gender, Department, and Grade point average) of 3 students. ID, Name Gender, Dept, and GPA are fields of this structure. They are used to represent Identification number, Name, Gender, Department, and Grade point average respectively.

27 Creating Array of struct Syntax: Example: class-name[] array-name = new class-name[size]; using System; class Test { class StdInfo { public int id; public string name; public string dept; } public static void Main() { StdInfo [] students = new StdInfo[50]; for (int i = 0; i < 50; i++) students[i] = new StdInfo(); : } using System; class Test { class StdInfo { public int id; public string name; public string dept; } public static void Main() { StdInfo [] students = new StdInfo[50]; for (int i = 0; i < 50; i++) students[i] = new StdInfo(); : } Create an array for storing 50 references to StdInfo objects Create an actual object StdInfo for each reference in the array

28 Example 1 : How to define and declare an array of struct. namespace Array_Struct1 { class ClassArray { const int n = 5; struct Employee { public string ID; public string Name; public int Salary; public char Gender; public bool Status; } static void Main(string[] args) { Employee [] a = new Employee[n]; ……………… ; } The structure shown below is an array of struct which can be used to store information of 5 employees. Format of the variable declaration of an one- dimensional array of struct.

29 How to reference (access) each element of an array of struct. namespace Array_Struct1 { class ClassArray { const int n = 5; struct Employee { public string ID; public string Name; public int Salary; public char Gender; public bool Status; } static void Main(string[] args) { Employee [] a = new Employee[n]; for (int k = 0; k < n; k++) { a[k].ID = Console.ReadLine(); a[k].Name = Console.ReadLine(); a[k].Salary = int.Parse(Console.ReadLine()); a[k].Gender = char.Parse(Console.ReadLine()); a[k].Status = bool.Parse(Console.ReadLine()); } } } Element of an array of struct can be referenced by the following format: array variable[index].field

30 ID Name Salary Gender Status 0 E9001 Vallapa 4500 F False 1 E9002 Pongrit 4800 M True 2 E9003 Panita 3480 F False 3 E9004 Veekit 4780 M True 4 E9005 Luxana 4320 F False a[0].ID = E9001 a[0].Name = Vallapa a[0].Salary = 4,500 a[0].Gender = F a[0].Status = False //not married yet a[1].ID = E9002 a[1].Name = Pongrit a[1].Salary = 4,800 a[1].Gender = M a[1].Status = True //already married ……… a[4].ID = E9005 ……………. The first Record The second Record

31 Array of struct: Array of (references to) struct of type StdInfo that store information of several records. struct of type StdInfo (with reference variable) that store only one record Paula ME ID: Name: Dept: Lisa EE ID: Name: Dept: Uma CPE ID: Name: Dept: Paula ME ID: Name: Dept: struct var A struct variable with struct data type.

32 Accessing Details class StdInfo { public int ID; public string Name; public string Dept; } static void Main() { StdInfo[] students; students = new StdInfo[4]; : students[2].Name = "Ariya"; } class StdInfo { public int ID; public string Name; public string Dept; } static void Main() { StdInfo[] students; students = new StdInfo[4]; : students[2].Name = "Ariya"; } Paula ENVE ID: Name: Dept: Lisa ME ID: Name: Dept: Uma CPE ID: Name: Dept: Masha EE ID: Name: Dept: Ariya

33 Example 2 : How to define and declare an array of struct. class Class1 { const int n = 5; struct Employee { public string ID; public string Name; public int Salary; public char Gender; public bool Status; public double Insurance; } static void Main(string[] args) { person [] a = new person[n]; for (int k = 0; k < n; k++) { a[k].ID = Console.ReadLine(); a[k].Name = Console.ReadLine(); a[k].salary = int.Parse(Console.ReadLine()); a[k].gender = char.Parse(Console.ReadLine()); a[k].status = bool.Parse(Console.ReadLine()); } for (int k = 0; k < n; k++) { if ((a[k].gender == 'F') && (a[k].status)) a[k].insurance = a[k].salary * 0.2; else a[k].insurance = 0.0; } for (int k = 0; k < n; k++) { Console.Write("{0} {1} {2} ", a[k].ID, a[k].Name, a[k].salary); Console.Write("{0} {1} {2}",a[k].gender, a[k].status, a[k].insurance); Console.WriteLine(); }

34 Example 3 : How to define and declare an array of struct. Assume that we have 5 lines of the population data of a community during the period 1950 to Each line of the data contains a year and the corresponding population. The data lines are in ascending order by year. Write the program to read the data and determine the two consecutive years in which the percentage increase in population was the greatest. (The output is the two consecutive years with the largest percentage increase in population. Input/Output Description YearPopulation [(56 – 82)/82 * 100 = -32% [(71 – 56)/56 * 100 = 27% [(86 – 71)/71 * 100 = 21% [(102 – 86)/86 * 100 = 18%

35 class Class1 { struct CensusData { public int year; public int pop; } static void Main(string[] args) { Console.Write("How many years :"); int n = int.Parse(Console.ReadLine()); double [] percent = new double[n-1]; double bestPercent = 0.0; int year1 = 0, year2 = 0, bestYear = 0; CensusData [] census = new CensusData [n]; for (int k = 0; k < n; k++) { census[k].year = int.Parse(Console.ReadLine()); census[k].pop = int.Parse(Console.ReadLine()); } for (int k = 0; k < (n-1); k++) percent[k] = 0.0; for (int k = 0; k < (n-1); k++) { percent[k] = (census[k+1].pop - census[k].pop)*100/census[k].pop; if ((percent[k] > bestPercent) || (k == 0)) { bestPercent = percent[k]; bestYear = census[k+1].year; } for (int k = 0; k<(n-1); k++) Console.Write("{0} ",percent[k]); Console.WriteLine(); year1 = bestYear - 1; year2 = bestYear; Console.WriteLine("Greatest between {0} and {1}",year1, year2); } }

36 A struct data type may consists of sub-struct. namespace SubStruct { class Program { public struct DOB { public byte D; public string M; public int Y; } public struct StdInfo { public string ID; public string Name; public DOB BirthDate; public double GPA; } public static void Main(string[] args) { int n = 2, k; StdInfo [] Student = new StdInfo[n]; for (k=0; k<n; k++) { Student[k].ID = Console.ReadLine(); Student[k].Name = Console.ReadLine(); Student[k].BirthDate.D = byte.Parse(Console.ReadLine()); Student[k].BirthDate.M = Console.ReadLine(); Student[k].BirthDate.Y = int.Parse(Console.ReadLine()); Student[k].GPA = double.Parse(Console.ReadLine()); } for (k=0; k<n; k++) if ((Student[k].BirthDate.D == 1) && (Student[k].BirthDate.M == "January")) Console.WriteLine("HellO {0} happy birth day and new year", Student[k].Name); } } }

37 Parameter passing between methods If an actual parameter is struct, it can be passed to formal parameter whose data type is also struct. An information passed from actual parameter (of caller) to formal parameter (of called method) is value of struct variable. However, if an actual parameter is an array of struct, an information passed between caller and called methods must be a memory address instead of value of struct variable. An example (example2) as shown in the next 2 slides.

38 Passing Struct variable between methods : The value of struct variable Book is passed to BK. An example (example1) is shown on the next slide. ISBN Yuen Poovaravan ID: price: author: Book ISBN Yuen Poovaravan ID: price: author: BK Called method Calling method Book is a variable whose data type is struct. BK is a variable whose data type is also struct.

39 namespace Cons_Struct4 { class Class1 { public struct bookType { public string ID; public int price; public string author; } static bookType ChangePrice(bookType BK) { BK.price = BK.price * 2; Console.WriteLine("Display at ChangePrice() "); Console.WriteLine("{0} {1} {2}", BK.ID, BK.price, BK.author); return BK; } static void Main(string[] args) { bookType Book, Result; Book.ID = Console.ReadLine(); Book.price = int.Parse(Console.ReadLine()); Book.author = “Yuen Poovaravan”; Result = ChangePrice(Book); Console.WriteLine("Display at Main()"); Console.WriteLine("{0} {1} {2}", Result.ID, Result.price, Result.author); } Example 1 : Passing a struct variable between methods

40 ISBN Yuen Poova ID: price: author: ISBN Peera Wat ID: price: author: ISBN Siri Ong ID: price: author: Memory address is passed. Calling method Called method Passing an array of struct between methods : Memory address of actual parameter is passed to formal parameter.

41 class ClassStruct { public struct bookType { public string ID; public int price; public string author; } static void ChangePrice (bookType[] BK, int n) { for (int k = 0; k < n; k++) BK[k].price = BK[k].price * 2; Console.WriteLine("Display at ChangePrice() "); for (int k = 0; k < n; k++) Console.WriteLine("{0} {1} {2}", BK[k].ID, BK[k].price, BK[k].author); } static void Main(string[] args) { int n; bookType [] Book Console.WriteLine("Enter number of records : "); n = int.Parse(Console.ReadLine()); Book = new bookType[n]; for (int k = 0; k<n; k++) { Book[k].ID = Console.ReadLine(); Book[k].price = int.Parse(Console.ReadLine()); Book[k].author = Console.ReadLine(); } ChangePrice(Book, n); Console.WriteLine("Display at Main()"); for (int k = 0; k < n; k++) Console.WriteLine("{0} {1} {2}", Book[k].ID, Book[k].price, Book[k].author); } } } Example 2 : Passing an array of struct between methods.

42 Example 3 : Student Records Get N students' information with 3 fields   ID, Name, Score Then output a table of information First, we define a class as shown: class StdInfo { public int id; public string name; public int score; } class StdInfo { public int id; public string name; public int score; }

43 ReadInfo Method Reads all information for each student Returns an object of class StdInfo static StdInfo ReadInfo() { StdInfo info = new StdInfo(); Console.Write("ID: "); info.id = int.Parse(Console.ReadLine()); Console.Write("Name: "); info.name = Console.ReadLine(); Console.Write("Score: "); info.score = int.Parse(Console.ReadLine()); return info; } static StdInfo ReadInfo() { StdInfo info = new StdInfo(); Console.Write("ID: "); info.id = int.Parse(Console.ReadLine()); Console.Write("Name: "); info.name = Console.ReadLine(); Console.Write("Score: "); info.score = int.Parse(Console.ReadLine()); return info; }

44 ShowInfo Method Takes a StdInfo and displays the information on screen Returns nothing static void ShowInfo(StdInfo info) { Console.WriteLine("{0,3} {1,-10} {2,2}", info.id, info.name, info.score); } static void ShowInfo(StdInfo info) { Console.WriteLine("{0,3} {1,-10} {2,2}", info.id, info.name, info.score); }

45 Put Them All Together using System; class StdRecords { // Define class StdInfo here // Define ReadInfo() here // Define ShowInfo() here static void Main() { Console.Write("How many students? "); int n = int.Parse(Console.ReadLine()); StdInfo[] students = new StdInfo[n]; for (int i = 0; i < n; i++) students[i] = ReadInfo(); for (int i = 0; i < n; i++) ShowInfo(students[i]); } using System; class StdRecords { // Define class StdInfo here // Define ReadInfo() here // Define ShowInfo() here static void Main() { Console.Write("How many students? "); int n = int.Parse(Console.ReadLine()); StdInfo[] students = new StdInfo[n]; for (int i = 0; i < n; i++) students[i] = ReadInfo(); for (int i = 0; i < n; i++) ShowInfo(students[i]); }