Structures in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR.

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

Transcript of Structures in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR.

Page 1: Structures in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1  ADNAN BABAR MT14028 CR.

Structures in C++

U N I V E R S I T Y O F T H E P U N J A B( G U J R A N W A L A C A M P U S )

1

www.msc-it-m.wapka.mobi/index.xhtml

ADNAN BABARMT14028CR

Page 2: Structures in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1  ADNAN BABAR MT14028 CR.

2

ObjectivesThe contents we are going to cover in this chapter:

• Structures• Array of Structures• Nested Structures• Union• Enumerations

Page 3: Structures in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1  ADNAN BABAR MT14028 CR.

3

StructuresIntroduction

• 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

Page 4: Structures in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1  ADNAN BABAR MT14028 CR.

4

StructuresStructure 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

CONTENTS

Structures

Array of Structures

Nested Structures

Union

Enumerations

Page 5: Structures in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1  ADNAN BABAR MT14028 CR.

5

Structure Variable / InstanceDefining 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;

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

Page 6: Structures in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1  ADNAN BABAR MT14028 CR.

6

Structure VariableAccessing 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;

CONTENTS

Structures

Array of Structures

Nested Structures

Union

Enumerations

Memory allocation

Page 7: Structures in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1  ADNAN BABAR MT14028 CR.

7

Structure Example#include <iostream.h>#include <conio.h>

/*******Structure definition*******/struct part //declare a structure{

int modelnumber; //ID number of widgetint partnumber; //ID number of widget partfloat cost; //cost of part

};/******* End of Structure *******/

int main(){

//define a structure variablepart part1;

//give values to structure memberspart1.modelnumber = 6244;part1.partnumber = 373;part1.cost = 217.55F;

//display structure memberscout <<"Model: "<< part1.modelnumber;cout <<"\nPart: " << part1.partnumber;cout <<"\nCosts $" << part1.cost << endl;return 0;

}

CONTENTS

Structures

Array of Structures

Nested Structures

Union

EnumerationsModel: 6244Part: 373Costs $217.55Press any key to continue . . .

Page 8: Structures in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1  ADNAN BABAR MT14028 CR.

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.

• SyntaxstructureName Identifier = {val1, val2, … , valN} ;

• Examplepart tyre = { 2011, 34, 13.50};

CONTENTS

Structures

Array of Structures

Nested Structures

Union

Enumerations

struct part{

int modelnumber; int partnumber;

float cost;};

Page 9: Structures in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1  ADNAN BABAR MT14028 CR.

9

Initializing Structure Variable• Example of Initialization of structure variable

#include <iostream.h>

////////////////////////////////////////////////////////////////struct part //specify a structure{

int modelnumber; // ID number of widgetint partnumber; // ID number of widget partfloat cost; // cost of part

};////////////////////////////////////////////////////////////////int main(){

//initialize variablepart part1 = { 2011, 34, 13.50 };

//display structure elementscout << "Model: " << part1.modelnumber;cout << "\nPart: " << part1.partnumber;cout << "\nCosts: $" << part1.cost << endl;return 0;

}

CONTENTS

Structures

Array of Structures

Nested Structures

Union

Enumerations

Model: 2011Part: 34Costs: $13.5Press any key to continue . . .

Page 10: Structures in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1  ADNAN BABAR MT14028 CR.

10

Assigning One Structure Variable to Other• A structure variable can be initialized by assigning another structure variable to it by

using assignment operator.

• Syntaxpart 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 <iostream.h>struct part //specify a structure{

int modelnumber; // ID number of widgetint partnumber; // ID number of widget partfloat 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;

}

CONTENTS

Structures

Array of Structures

Nested Structures

Union

Enumerations

Model: 2011Part: 34Costs: $13.5Press any key to continue . . .

Page 11: Structures in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1  ADNAN BABAR MT14028 CR.

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!

Marks

Student usman

Marks[0] Marks[1] Marks[2] Marks[3] Marks[4]

Roll_number

CONTENTS

Structures

Array of Structures

Nested Structures

Union

Enumerations

Page 12: Structures in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1  ADNAN BABAR MT14028 CR.

12

Array as Member of StructureAccessing Array Elements

• The array stored in a structure can be accessed by using the following1. Name of Structure Variable2. Dot Operator3. Name of Array4. 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 <iostream.h>#include <conio.h>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;

}

CONTENTS

Structures

Array of Structures

Nested Structures

Union

Enumerations

Page 13: Structures in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1  ADNAN BABAR MT14028 CR.

13

Array as Member of StructureInitializing 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 <iostream.h>#include <conio.h>#include <stdio.h>

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;

}

CONTENTS

Structures

Array of Structures

Nested Structures

Union

Enumerations Marks: 60Marks: 75Marks: 85Marks: 52Marks: 53

Page 14: Structures in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1  ADNAN BABAR MT14028 CR.

14

Array of StructuresArray 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.

• Examplestruct 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

Page 15: Structures in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1  ADNAN BABAR MT14028 CR.

15

Accessing Array of Structures

• 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];

Page 16: Structures in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1  ADNAN BABAR MT14028 CR.

16

Initializing Array of StructuresCONTENTS

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]

Page 17: Structures in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1  ADNAN BABAR MT14028 CR.

17

Nested StructureCONTENTS

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.

Page 18: Structures in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1  ADNAN BABAR MT14028 CR.

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)

Date (inner Structure)(day, month, year)

ahmad.dateOfBirth.year = 1940;

Page 19: Structures in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1  ADNAN BABAR MT14028 CR.

Program Example

19

CONTENTS

Structures

Array of Structures

Nested Structures

Union

Enumerations

Nested Strucuture#include <iostream.h>

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: 25DateOfBirth: 23 / 3 / 1940Press any key to continue . . .

Page 20: Structures in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1  ADNAN BABAR MT14028 CR.

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.

• Syntaxunion union_name

{member_type1 member_namel;member_type2 member_name2;member_type3 member_name3;… …member_typeN member_nameN;

};

Page 21: Structures in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1  ADNAN BABAR MT14028 CR.

Enumerations

21

CONTENTS

Structures

Array of Structures

Nested Structures

Union

Enumerations

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 1enum 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 2enum days_of_week {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday};

• VALUES: Monday = 0, Tuesday = 1 ,… , Sunday = 6

Page 22: Structures in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1  ADNAN BABAR MT14028 CR.

Enumerations

22

CONTENTS

Structures

Array of Structures

Nested Structures

Union

Enumerations

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

Page 23: Structures in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1  ADNAN BABAR MT14028 CR.

Program Example

23

CONTENTS

Structures

Array of Structures

Nested Structures

Union

Enumerations

#include <iostream.h>#include <conio.h>void main(){

enum year {Jan = 1, Feb, Mar, April, May, Jun, July, Aug, Sept, Oct, Nov, Dec}

year month; // declaring an enummonth = March;cout<<“The value of March: ” << month << endl;getch();

}OUTPUT:The value of March: 3