Presentation is loading. Please wait.

Presentation is loading. Please wait.

Programming Fundamental

Similar presentations


Presentation on theme: "Programming Fundamental"— Presentation transcript:

1 Programming Fundamental
Instructor Name: Lecture-21

2 Today’s Lecture Structure (Introduction) Structure Declaration
Accessing Structure Structure Initialization (Initialized List & Constructor) Structure & Functions Self Referential Structure Unions 2

3 Structure (struct) Introduction scores : 85 79 92 57 68 80 . . .
With array, we can only declare one data type per array. For different data type, we need another array declaration. It is single type aggregate data type. In some situations, we wish to group elements of different types scores : employee R. Jones Elm 6/12/55 $14.75 3

4 Structure (struct) Introduction
Struct overcomes this problem by declaring composite data types which can consist different types. A structure is a collection of related data items stored in one place and can be referenced by more than one names. These data items are different basic data types.  So, the number of bytes required to store them may also vary. A structure type is a user-defined composite type. It is composed of fields or members which can be different types (Heterogeneous). 4

5 Structure (struct) Introduction
Structures hold data that belong together. Examples: Student record: student id, name, major, gender, start year, … Bank account: account number, name, currency, balance, … Address book: name, address, telephone number, … In database applications, structures are called records. Individual components of a struct type are called members (or fields). Members can be of different types (simple, array or struct). A struct is named as a whole while individual members are named using field identifiers. Complex data structures can be formed by defining arrays of structs. 5

6 Structure Declaration
Structure (struct) Structure Declaration The syntax of structure declaration is as follows struct structure_name { type1 field1; type2 field2; typen fieldn; }; struct is a keyword that tells the compiler that a structure template is being declared Structure_name is a tag that identifies its data structure. Tag is not a variable; it is a label for the structure’s template. Note that there is a semicolon after the closing curly brace. 6

7 Structure Declaration Example
Structure (struct) Structure Declaration Example struct Student { int studentID; string name; short year; double gpa; }; struct names commonly begin with an uppercase letter Multiple fields of same type can be in a comma-separated list string name, address; structure tag structure members Notice the required ; 7

8 Structure Declaration More Example
Structure (struct) Structure Declaration More Example Example: struct StudentInfo{ int Id; int age; char Gender; double CGA; }; struct StudentGrade{ char Name[15]; char Course[9]; int Lab[5]; int Homework[3]; int Exam[2]; The “StudentInfo” structure has 4 members of different types. The “StudentGrade” structure has 5 members of different array types. 8

9 Structure Declaration More Example
Structure (struct) Structure Declaration More Example Example: struct BankAccount{ char Name[15]; int AcountNo[10]; double balance; Date Birthday; }; struct StudentRecord{ int Id; char Dept[5]; char Gender; The “BankAcount” structure has simple, array and structure types as members. The “StudentRecord” structure has 4 members. 9

10 Declaring Structure Variable
Structure (struct) Declaring Structure Variable struct motor p, q, r; Declares and sets aside storage for three variables – p, q, and r – each of type struct motor struct motor M[25]; Declares a 25-element array of struct motor; allocates 25 units of storage, each one big enough to hold the data of one motor struct motor *m; Declares a pointer to an object of type struct motor 10

11 Declaring Structure Variable
Structure (struct) Declaring Structure Variable Struct struct declaration does not allocate memory or create variables To define variables, use structure tag as type name Student s1; studentID name year gpa s1 11

12 Accessing members of a struct
Structure (struct) Accessing members of a struct Use the dot (.) operator to refer to members of struct variables Let struct motor p; struct motor q[10]; Then p.volts — is the voltage p.amps — is the amperage p.phases — is the number of phases p.rpm — is the rotational speed q[i].volts — is the voltage of the ith motor q[i].rpm — is the speed of the ith motor 12

13 Accessing members of a struct (continued)
Structure (struct) Accessing members of a struct (continued) Let struct motor *p; Then (*p).volts — is the voltage of the motor pointed to by p (*p).phases — is the number of phases of the motor pointed to by p The (*p).member notation is a irritant Clumsy to type; need to match ( ) Too many keystrokes This construct is so widely used that a special notation was invented, i.e., p->member, where p is a pointer to the structure Because '.' operator has higher precedence than unary '*' Why the parentheses? 13

14 Displaying members of a struct
Structure (struct) Displaying members of a struct To display the contents of a struct variable, you must display each field separately, using the dot operator Wrong: cout << s1; // won’t work! Correct: cout << s1.studentID << endl; cout << s1.name << endl; cout << s1.year << endl; cout << s1.gpa; 14

15 Initializing Structure (struct)
Initializing a Structure Cannot initialize members in the structure declaration, because no memory has been allocated yet struct Student // Illegal { // initialization int studentID = 1145; string name = "Alex"; short year = 1; float gpa = 2.95; }; Structure members are initialized at the time a structure variable is created Can initialize a structure variable’s members with either an initialization list a constructor 15

16 Initializing Structure (struct)
Using an Initialized List An initialization list is an ordered set of values, separated by commas and contained in { }, that provides initial values for a set of data members {12, 6, 3} // initialization list with 3 values Order of list elements matters: First value initializes first data member, second value initializes second data member, etc. Elements of an initialization list can be constants, variables, or expressions {12, W, L/W + 1} // initialization list with 3 items 16

17 Initializing Structure (struct)
Initialization List Example struct Dimensions { int length, width, height; }; Dimensions box = {12,6,3}; box length 12 width 6 height 3 17

18 Initializing Structure (struct)
Partial Initialization Can initialize just some members, but cannot skip over members Dimensions box1 = {12,6}; //OK Dimensions box2 = {12,,3}; //illegal Problem with Initialization List Can’t omit a value for a member without omitting values for all following members Does not work on most modern compilers if the structure contains any string objects Will, however, work with C-string members 18

19 Initializing Structure (struct)
Using Constructor for Initialization struct A constructor is a special function that can be a member of a structure It is normally written inside the struct declaration Its purpose is to initialize the structure’s data members Unlike most functions, a constructor is not called; instead, it is automatically invoked when a structure variable is created The constructor name must be the same as the structure name (i.e. the struct tag) The constructor must have no return type 19

20 Initializing Structure (struct)
A Structure with Constructor struct Dimensions { int length, width, height; // Constructor Dimensions(int L, int W, int H) {length = L; width = W; height = H;} }; Passing Arguments to a Constructor Create a structure variable and follow its name with an argument list Example: Dimensions box3(12, 6, 3); 20

21 Initializing Structure (struct)
A Constructor with Default Arguments struct Dimensions { int length, width, height; // Constructor Dimensions(int L=1, int W=1, int H=1) {length = L; width = W; height = H;} }; Default Constructor Arguments Example Dimensions box4(12, 6, 3); //Create a box with all dimensions given Dimensions box5(12, 6); //Create a box using default value 1 for height Dimensions box6; //Create a box using all default values 21

22 Nested Structure (struct)
A structure can have another structure as a member. struct PersonInfo { string name, address, city; }; struct Student int studentID; PersonInfo pData; short year; double gpa; 22

23 Nested Structure (struct)
Members of Nested Structure Use the dot operator multiple times to dereference fields of nested structures Student s5; s5.pData.name = “Aslam"; s5.pData.city = “Lahore"; 23

24 Self Referential Structure
A Structure which contain a reference to itself. A common occurrence of this in a structure which describes a node for a link list. Each node needs a reference to the next node in the chain. struct item { char *s; struct item *next; } I.e., an item can point to another item … which can point to another item … which can point to yet another item … etc. Thereby forming a list of items Yes! This is legal! 24

25 Structures as Function Arguments
Structure & Functions Structures as Function Arguments May pass members of struct variables to functions computeGPA(s1.gpa); May pass entire struct variables to functions showData(s5); Can use reference parameter if function needs to modify contents of structure variable Notes on Passing Structure Using a value parameter for structure can slow down a program and waste space Using a reference parameter speeds up program, but allows the function to modify data in the structure To save space and time, while protecting structure data that should not be changed, use a const reference parameter void showData(const Student &s) // header 25

26 Returning Structure from Function
Structure & Functions Returning Structure from Function Function can return a struct Student getStuData(); // prototype s1 = getStuData(); // call Function must define a local structure for internal use to use with return statement 26

27 Returning Structure Example
Structure & Functions Returning Structure Example Student getStuData() { Student s; // local variable cin >> s.studentID; getline(cin, s.pData.name); getline(cin, s.pData.address); getline(cin, s.pData.city); cin >> s.year; cin >> s.gpa; return s; } 27

28 28


Download ppt "Programming Fundamental"

Similar presentations


Ads by Google