Presentation is loading. Please wait.

Presentation is loading. Please wait.

Structures in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 www.msc-it-m.wapka.mobi/index.xhtml ADNAN BABAR MT14028 CR.

Similar presentations


Presentation on theme: "Structures in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 www.msc-it-m.wapka.mobi/index.xhtml ADNAN BABAR MT14028 CR."— Presentation transcript:

1 Structures in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 www.msc-it-m.wapka.mobi/index.xhtml ADNAN BABAR MT14028 CR

2 Objectives The contents we are going to cover in this chapter: Structures Array of Structures Nested Structures Union Enumerations 2

3 Structures Introduction A simple variable can store only one value at a time. A structure is a collection of simple variables. The variables in a structure can be of different data types that can be referenced with single name. The data items in a structure are called structure elements, members or fields. The structures are used to join simple variables together to form a bit complex variables. The difference between an array and a structure is that array contains set of variables of same data type. However, a structure may consist of different data types. The user can define a new data type that may contain different types of data with the help structures. CONTENTS Structures Array of Structures Nested Structures Union Enumerations 3

4 Structures Structure Declaration A structure is declared by using C++ keyword struct followed by the structure name followed by a pair of curly braces {}. The structure members are defined with their data-type inside the opening and closing curly braces. The closing brace is ended with a semicolon. The declaration tells the compiler about the details of the structure. Syntax struct structName { dataType1 identifier1; dataType2 identifier2; : dateTypeN identifierN; }; Example of Structure 4 CONTENTS Structures Array of Structures Nested Structures Union Enumerations

5 Structure Variable / Instance Defining a Structure variable The structure variable can be defined after the declaration of a structure. The process of defining a structure variable is same as defining a variable of basic types such as int and char. The definition tells the compiler to allocate memory space for the variable. The compiler automatically allocates sufficient memory according to the elements of the structure. Syntax: structName Identifier; Example: (Assuming previously defined struct part ) part p1; 5 CONTENTS Structures Array of Structures Nested Structures Union Enumerations The structure variable p1 will occupy bytes in the memory as follows. int modelnumber (2 bytes) int partnumber (2 bytes) float cost (4 bytes) Total number of bytes p1 contains in memory is 8 bytes

6 Structure Variable Accessing Members of Structure Variable Any member of a structure variable can be accessed by using dot operator or member access operator. The name of the structure variable is written on the left side of the dot operator. The name of member variable is written on right side of the dot operator. Syntax: StructureVariable.MemberVariable; Example: part part1; part part2; part part3; part2.modelnumber = 4343; 6 CONTENTS Structures Array of Structures Nested Structures Union Enumerations Memory allocation

7 Structure Example #include /*******Structure definition*******/ struct part//declare a structure { int modelnumber;//ID number of widget int partnumber;//ID number of widget part float cost;//cost of part }; /******* End of Structure *******/ int main() { //define a structure variable part part1; //give values to structure members part1.modelnumber = 6244; part1.partnumber = 373; part1.cost = 217.55F; //display structure members cout <<"Model: "<< part1.modelnumber; cout <<"\nPart: " << part1.partnumber; cout <<"\nCosts $" << part1.cost << endl; return 0; } 7 CONTENTS Structures Array of Structures Nested Structures Union Enumerations Model: 6244 Part: 373 Costs $217.55 Press any key to continue...

8 Initializing Structure Variable The process of assigning values to structure elements is called Initialization of Structure variables. The assignment operator = is used for initialization. The declaration of structure variable is specified on the left side of assignment operator. The values for initialization are written on the right side of assignment operator surrounded by the curly braces. The values are written in the same sequence in which they are specified in structure declaration. Each value is separated by comma. Syntax structureName Identifier = {val1, val2, …, valN} ; Example part tyre = { 2011, 34, 13.50}; 8 CONTENTS Structures Array of Structures Nested Structures Union Enumerations struct part { int modelnumber; int partnumber; float cost; };

9 Initializing Structure Variable Example of Initialization of structure variable #include //////////////////////////////////////////////////////////////// struct part//specify a structure { int modelnumber;// ID number of widget int partnumber;// ID number of widget part float cost;// cost of part }; //////////////////////////////////////////////////////////////// int main() { //initialize variable part part1 = { 2011, 34, 13.50 }; //display structure elements cout << "Model: " << part1.modelnumber; cout << "\nPart: " << part1.partnumber; cout << "\nCosts: $" << part1.cost << endl; return 0; } 9 CONTENTS Structures Array of Structures Nested Structures Union Enumerations Model: 2011 Part: 34 Costs: $13.5 Press any key to continue...

10 Assigning One Structure Variable to Other A structure variable can be initialized by assigning another structure variable to it by using assignment operator. Syntax part part1 = {2011, 34, 13.5}; part part2 = part1; // assign part1 to part2 The first line declares a structure variable part1 and initializes it. The second line declares another structure variable part2 and initializes it another same structure variable. One structure variable can be assigned to another structure variable only if both are of same type. #include struct part//specify a structure { int modelnumber;// ID number of widget int partnumber;// ID number of widget part float cost;// cost of part }; int main() { part part1 = { 2011, 34, 13.50 }; part part2 = part1; // Assignment Statement cout << "Model: " << part2.modelnumber; cout << "\nPart: " << part2.partnumber; cout << "\nCosts: $" << part2.cost << endl; return 0; } 10 CONTENTS Structures Array of Structures Nested Structures Union Enumerations Model: 2011 Part: 34 Costs: $13.5 Press any key to continue...

11 Array as Member of Structure A structure may consist of different types of data. The member variables can be simple data types such as int, char and float. The member variables can also be complex like arrays. Example struct Student { int Roll_number; int Marks[5]; }; The above example declares a structure Student with two members. The first member is a simple variable of type int. The second member is an array of integers. It can be used to store the marks of five subjects. As, a student can have only one roll number. For marks we declare an Array! 11 Marks Student usman Marks[0]Marks[1]Marks[2]Marks[3]Marks[4] Roll_number CONTENTS Structures Array of Structures Nested Structures Union Enumerations

12 Array as Member of Structure Accessing Array Elements The array stored in a structure can be accessed by using the following 1.Name of Structure Variable 2.Dot Operator 3.Name of Array 4.Index of desired element Structure Variable – in which an array is defined. Dot Operator or Member Access Operator – It is used to refer the array. Index – the index is used to access the individual element of the array. Example #include struct student { int roll_number; int marks[5]; }; int main() { student usman; usman.roll_number = 101; for(int i = 0; i < 5 ; i++) usman.marks[i] = 1 + rand() % 100 ; // marks 66 ~ 99 cout << endl; for(int i = 0; i < 5 ; i++) cout << usman.marks[i] << endl; getch(); return 0; } 12 CONTENTS Structures Array of Structures Nested Structures Union Enumerations

13 Array as Member of Structure Initializing a Structure with Array as Member The structure that contains an array as member variable can be initialized in the same the same way as initializing a simple structure variable. The values are written in braces and each value is separated by comma. additionally, the values for the member array are written in nested braces, in proper order. Example #include struct student { int roll_number; int marks[5]; }; int main() { student usman = {101, {60,75,85,52,53}}; for(int i = 0; i < 5 ; i++) cout << "Marks: " << usman.marks[i] << endl; getch(); return 0; } 13 CONTENTS Structures Array of Structures Nested Structures Union Enumerations Marks: 60 Marks: 75 Marks: 85 Marks: 52 Marks: 53

14 Array of Structures 14 Array of Structures An array is a collection of same type of data. An array can be of simple data type such as int, char or float etc. Similarly, an array can be of user-defined type such as a structure. An array of structure is a type of array in which each element contains a complete structure. It can be used to store many records. Example struct Book { int BookID; int Pages; float Price; }; Book b[3]; The above example declares a structure Book. It defines an array b[3] of structure Book. The array can store the records of three books. CONTENTS Structures Array of Structures Nested Structures Union Enumerations

15 Accessing Array of Structures 15 The array is accessed by using its index. The structure is accessed by using dot operator. An array of structures can be accessed as follows: Example: Record of First Book e.g. b[0] b[0].BookID= 154; b[0].Pages = 1036; b[0].Price = 425; And simply… cout << “Book ID: ” << b[0].BookID << endl; cout << “Book Pages: ” << b[0].Pages << endl; cout << “Book Price: ” << b[0].Price << endl; CONTENTS Structures Array of Structures Nested Structures Union Enumerations Book b[3];

16 Initializing Array of Structures 16 CONTENTS Structures Array of Structures Nested Structures Union Enumerations An array of structures can be initialized at the time of declaration by writing the values in braces. The values for each element of the array are written in separate inner braces. Example struct Book { int BookID; int Pages; float Price; }; Book b[3] = { { 11, 125, 50.0}, { 31, 480, 185.75}, { 45, 360, 145.50} }; The above example declares an array of structure and initializes it. The values are written in braces with the help of nested braces, separated by commas, to refer each book in the Structure Array. Each inner pair of braces is used to initialize one element of the array. b[0] b[1] b[2]

17 Nested Structure 17 CONTENTS Structures Array of Structures Nested Structures Union Enumerations A structure within a structure is known as Nested Structure. A nested structure is created when the member of a structure is itself a structure. Example struct Date { int dat; int month; int year; }; struct Student { char name[20]; int age; Date dateOfBirth; }; Above example defines two structures Date and Student. The structure Date contains simple member variables day, month, year of data type int. Second structure Student contains three member variables. The first two members are of basic data type, there is no ambiguity. But the third member of Structure Student is itself a structure variable.

18 Nested Structure 18 CONTENTS Structures Array of Structures Nested Structures Union Enumerations Accessing Members of Nested Structure The member variable of nested structure can be accessed using multiple dot operators. The first dot operator refers the member variable of outer structure. The second dot operator refers the inner structure and so on. Example ( Previous Slide, we have defined Nested Structure Date & Student ) Student ahmad; // ahmad further contains a structure We Assign values statically… Student ahmad; ahmad.name = "Ahmad"; ahmad.age = 25; ahmad.dateOfBirth.day = 23; ahmad.dateOfBirth.month = 3; ahmad.dateOfBirth.year = 1940; The above line creates a structure variable ahmad of type Student. It is a nested structure that contains another structure variable dateOfBirth of type Date as its member. The following statements can be used to store values in the above nested structure: The first statement uses one dot operator as it refers to simple member variable of the structure. The last three statements uses two dot operators as they refer to the members of the nested structure variables. Student (Outer Structure) (name, age, dateOfBirth) Student (Outer Structure) (name, age, dateOfBirth) Date (inner Structure) (day, month, year) Date (inner Structure) (day, month, year) ahmad.dateOfBirth.year = 1940;

19 Program Example 19 CONTENTS Structures Array of Structures Nested Structures Union Enumerations Nested Strucuture #include struct Date { int day; int month; int year; }; struct Student { int rollNumber; int age; Date dateOfBirth; }; int main() { Student ahmad; ahmad.rollNumber = 123; ahmad.age = 25; ahmad.dateOfBirth.day = 23; ahmad.dateOfBirth.month = 3; ahmad.dateOfBirth.year = 1940; cout << "Student Data\n" << endl; cout << “Roll Number: " <<ahmad.rollNumber; cout << ", Age: " <<ahmad.age; cout << "\nDateOfBirth: " << ahmad.dateOfBirth.day << " / " << ahmad.dateOfBirth.month <<" / "<< ahmad.dateOfBirth.year << endl; return 0; } Student Data Roll Number: 123, Age: 25 DateOfBirth: 23 / 3 / 1940 Press any key to continue...

20 Union 20 CONTENTS Structures Array of Structures Nested Structures Union Enumerations Union Unions are similar to structures in certain aspects. Unions are used to group together variables of different data types. The individual members can be accessed using dot operator. The difference between structure and union is in the allocation of memory space. A structure allocates total space required for a structure variable. However, a union allocates the space required by one element that occupies the maximum size. Syntax union union_name { member_type1 member_namel; member_type2 member_name2; member_type3 member_name3;… member_typeN member_nameN; };

21 Enumerations 21 CONTENTS Structures Array of Structures Nested Structures Union Enumerations Enumerations are used to create new data types. An enumeration consists of a list of values. Each value has a unique number i.e. Integer CONSTANT starting from 0. An enumeration may contain the values which are different from the values of fundamental data types. Syntax enum identifier { valuel, value2, value3 }; Example 1 enum colors {black, blue, green, cyan, red, purple, yellow, white}; The above enumeration does not contain any fundamental data type in the declaration. The list of values in braces indicates the possible values that can be stored in a variable of type colors. colors mycolor; mycolor blue; Example 2 enum days_of_week {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday}; VALUES: Monday = 0, Tuesday = 1,…, Sunday = 6

22 Enumerations 22 CONTENTS Structures Array of Structures Nested Structures Union Enumerations Each value in an enumeration is always assigned an integer value. By default, the value starts from 0 and so on. However, the values can be assigned in different way also. Example enum week {Saturday=1,Sunday, Monday, Tuesday, Wednesday, Thursday, Friday); The value of Sunday is 2, Monday is 3 and so on..

23 Program Example 23 CONTENTS Structures Array of Structures Nested Structures Union Enumerations #include void main() { enum year {Jan = 1, Feb, Mar, April, May, Jun, July, Aug, Sept, Oct, Nov, Dec} year month;// declaring an enum month = March; cout<<“The value of March: ” << month << endl; getch(); } OUTPUT: The value of March: 3


Download ppt "Structures in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 www.msc-it-m.wapka.mobi/index.xhtml ADNAN BABAR MT14028 CR."

Similar presentations


Ads by Google