1 / 45

Struct Data Type

Struct Data Type. Computers and Programming (01204111). Outline. Array revisited Data encapsulation in C# Struct Data Type Struct Definition Struct variable declaration Struct variable reference Array of struct. Array a. a0=7. :. a2=10. 7. 3. 10. 5. 8. 17. a5=17. 0. 1. 2.

wint
Download Presentation

Struct Data Type

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Struct Data Type Computers and Programming (01204111)

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

  3. Array a a0=7 : a2=10 7 3 10 5 8 17 a5=17 0 1 2 3 4 5 a1=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?

  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]; : } }

  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]; : } } What a mess...

  6. Object studentInfo ID: 48500000 Name: Paula Dept: ME Advisor: Arthur Data Encapsulation • A mechanism that bundles multiple items of varying types into one item or "object" Advisor="Arthur" Dept="ME" ID=48500000 Name="Paula" • C# provides two kinds of data encapsulation: • struct and class • 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 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. Field

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

  10. Struct Definition • Struct Name and its structure must be defined first. We can place declaration of struct in 2 positions: • Between namespace and class (line 4 – 8) • Within a class. (line 11 – 15)

  11. Format of struct Definition <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 <public > struct StdInfo { public string ID; public string Name; public double GPA; }

  12. 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?) <public > struct Carstruct { public string Car_Id; public string Car_Name; public bool Imported; }

  13. Example 3 : Struct Definition The data structure named POINT to store record of a point of 3 dimensional axes (X, Y, Z) <public > struct POINT { public double X; public double Y; public double Z; } 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 LINE { public double X1; public double Y1; public double Z1; public double X2; public double Y2; public double Z2; }

  14. 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 POINT { public double X; public double Y; public double Z; } <public > 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; OR struct_name variable name = new struct_name();

  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()); …………..…. ; ……………… ; } } Or StdInfo STUDENT1 = new StdInfo(); 

  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-structurePOINT 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);   } 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. *** 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. } 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;

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

  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 (inti = 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. The structure shown below is an array of struct which can be used to store information of 5 employees. 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]; ……………… ; ……………… ; } } } 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. 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. ID: 49051234 struct var Name: Paula Dept: ME ID: 49051234 ID: 49052345 ID: 49053456 Name: Paula Name: Lisa Name: Uma Dept: ME Dept: EE Dept: CPE 0 1 2 A struct variable with struct data type. 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.

  32. 0 ID: 49051234 1 Name: Paula Dept: ENVE 2 ID: 49052345 3 Name: Lisa Dept: ME ID: 49053456 Name: Uma Dept: CPE ID: 49054567 Name: Masha Dept: EE 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"; } Ariya

  33. 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(); } } } Example 2 : How to define and declare an array of struct.

  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 YearPopulation 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. ID: ID: ISBN1234 ISBN1234 Book BK price: price: 750 750 author: author: Yuen Poovaravan Yuen Poovaravan 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 BK is a variable whose data type is also struct. Calling method Book is a variable whose data type is struct.

  39. Example 1 : Passing a struct variable between methods 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); } } }

  40. ID: ISBN1234 ID: ISBN3456 price: 750 price: 1200 author: Yuen Poova author: SiriOng ID: ISBN2345 price: 800 author: PeeraWat 0 0 1 1 2 2 Passing an array of struct between methods : Memory address of actual parameter is passed to formal parameter. Called method  Memory address is passed. Calling method 

  41. Example 2 : Passing an array of struct between methods. 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); } } }

  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; }

  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; }

  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); }

  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 (inti = 0; i < n; i++) students[i] = ReadInfo(); for (inti = 0; i < n; i++) ShowInfo(students[i]); } }

More Related