Struct Data TypeStruct Data Type
Computers and ProgrammingComputers and Programming(01204111)(01204111)
2
OutlineOutline Array revisited Data encapsulation in C# Struct Data Type
Struct Definition Struct variable declaration Struct variable reference Array of struct
3
Arrays RevisitedArrays 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=3a1=3
a2=10a2=10a0=7a0=7
a5=17a5=17:: 77 101033 55 171788
Array Array aa
00 2211 33 5544
4
ExampleExample Imagine that you have to write a program
To store 100 students' namesTo store 100 students' names That's simple; just use an arrayThat's simple; just use an array
...and their scores...and their scores Also simple; create another arrayAlso simple; create another array
...and also their ...and also their IDID, , departmentdepartment, , facultyfaculty, , advisoradvisor, etc, 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 ExampleMore 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 What a mess...mess...
6
Data EncapsulationData Encapsulation A mechanism that bundles multiple
items of varying types into one item or "object"
Dept="ME"Dept="ME"
Advisor="Arthur"Advisor="Arthur"
Name="Paula"Name="Paula"ID=48500000ID=48500000
48500000PaulaMEArthur
ID:Name:Dept:
Advisor:
Object studentInfo
• C# provides two kinds of data encapsulation:C# provides two kinds of data encapsulation: structstruct and and classclass• This course will focus on This course will focus on structstruct only. 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
ID StudName
Gender Dept GPA Status
E9001 Peerawat M CPE 2.97 0
………… ……… ……… ……… ……… ………
………… ……… ……… ……… ……… ………
FieldField
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 DefinitionStruct Definition• Struct variable declarationStruct variable declaration• struct variable referencestruct 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)
123456789101112131415161718192021
using System;namespace StructName{
public struct L1{ ..........................; ..........................;}class SampleStruct{
public struct L2{ …………….........; …………….........;}public static void Main(string[] args){ ………....................;}
}}
11
Format of struct Definition
<public > struct StdInfo{
public string ID;public string Name;public double GPA;
}
<public> 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
<public > 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
<public > 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.
<public > 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
<public > 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.
<public > struct LINE {
public POINT P1; // a starting point of straight linepublic 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{
<public > 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 declarationusing 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{
<public > 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);
}
E9001 Yuen 67,890 M True
a.ID a.Name a.Salary a.Gender a.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 structFrom 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
ID Name Gender Dept GPA
1 E9001 Peerawat M CPE 2.97
2 E9002 Panita F EE 3.78
3 E9003 Luxana F CPE 2.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];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 = E9001a[0].Name = Vallapaa[0].Salary = 4,500a[0].Gender = Fa[0].Status = False //not married yet
a[1].ID = E9002a[1].Name = Pongrita[1].Salary = 4,800a[1].Gender = Ma[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.
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";}
AriyaAriya
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 1954. 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 Year Population
1950 82
1951 56
1952 71
1953 86
1954 102
[(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.
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
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
ReadInfoReadInfo Method 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
ShowInfoShowInfo Method 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]); }}