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

Slides:



Advertisements
Similar presentations
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Introduction Structures –Collections of related.
Advertisements

Chapter 10 C Structures, Unions, Bit Manipulations and Enumerations Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc.
Chapter 10 C Structures, Unions, Bit Manipulations, and Enumerations.
C How to Program, 6/e © by Pearson Education, Inc. All Rights Reserved.
Structure.
True or false A variable of type char can hold the value 301. ( F )
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 10 - C Structures, Unions, Bit Manipulations,
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 10 - Structures, Unions, Bit Manipulations, and Enumerations Outline 10.1Introduction 10.2Structure.
Data Type. A data type defines a set of values that a variable can store along with a set of operations that can be performed on that variable. Common.
Multidimensional Arrays C++ also allows an array to have more than one dimension. For example, a two-dimensional array consists of a certain number of.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 23P. 1Winter Quarter Structs and Enumeration.
Arrays in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR
CCSA 221 Programming in C CHAPTER 9 WORKING WITH STRUCTURES 1 ALHANOUF ALAMR.
CCSA 221 Programming in C CHAPTER 14 MORE ON DATA TYPES 1 ALHANOUF ALAMR.
1 Structures. Structure (struct) Definition A Structure is a container, it can hold a bunch of things. –These things can be of any type. Structures are.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 11 Structured Data.
Learners Support Publications Classes and Objects.
User Defined Data Types - updated Chapter 10: User Defined Data Types Objectives: In this chapter you will learn about, Introduction Declaring.
1 Mr. Muhammad Hanif Lecturer Information Technology MBBS Campus Dadu University of SIndh.
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 23P. 1Winter Quarter Structs and Enumeration Lecture 23.
 Introduction to Computer Science COMP 51 – Fall 2012 – Section 2 Structures.
Conditional Structures UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) ADNAN BABAR MT14028 CR
C++ Programming Basic Learning Prepared By The Smartpath Information systems
Compound Statements If you want to do more than one statement if an if- else case, you can form a block of statements, or compound statement, by enclosing.
Chapters 1-5 Review C++ Class. Chapter 1 – the big picture Objects Class Inheritance Reusability Polymorphism and Overloading.
16. STRUCTURES, UNIONS, AND ENUMERATIONS. Declaring Structures A structure is a collection of one or more components (members), which may be of different.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 11: Structured Data.
Array, Structure and Union
 2007 Pearson Education, Inc. All rights reserved C Structures, Unions, Bit Manipulations and Enumerations.
Copyright © 2012 Pearson Education, Inc. Chapter 11: Structured Data.
Programming Fundamentals. Today’s Lecture The Conditional Operator Logical Operators Structures Enumerations.
ENUMERATED DATATYPES. USER DEFINED DATA TYPES  Data Type Defined By Programmer  Allows Use Of More Complex Data  Typically Defined Globally So Variables.
Data Structure and c K.S.Prabhu Lecturer All Deaf Educational Technology.
1 CSC241: Object Oriented Programming Lecture No 02.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
Chapter 10 Structures, Unions, Bit Manipulations, and Enumerations Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering.
© Oxford University Press All rights reserved. CHAPTER 8 STRUCTURES.
CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi.
CCSA 221 Programming in C CHAPTER 9 WORKING WITH STRUCTURES 1.
Structures and Enumerations Introduction Structure definitions Nested structure Referring and initializing structure elements Passing structures to a function.
1 CSC103: Introduction to Computer and Programming Lecture No 24.
1 EPSII 59:006 Spring HW’s and Solutions on WebCT.
Weekly C-minar Week 0. Today: Steps of the compile Basic inclusion/syntax rules Low-cost containment Debugging.
Review Pointer Pointer Variables Dynamic Memory Allocation Functions.
Introduction to Computers and Programming Class 24 Structures (structs) Professor Avi Rosenfeld.
Array in C++ / review. An array contains multiple objects of identical types stored sequentially in memory. The individual objects in an array, referred.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 11: Structured Data.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 11: Structured Data.
Structure A collection of values (members) struct date{ int day; char month[10]; int year; }; Declare a structure variable struct date today; struct struct_name.
Simple Data Types Chapter Constants Revisited t Three reasons to use constants –Constant is recognizable –Compiler prevents changes in value.
STRUCTURES. INTRODUCTION A structure is same as that of records. It stores related information about an entity. Structure is basically a user defined.
Programming Fundamentals Enumerations and Functions.
1 1  Lecture 11 – Structured Data FTMK, UTeM – Sem /2014.
Chapter 6. Character String Types It is one in which the values consists of sequences of characters. How to Define a variable contain a string? In a programming.
Chapter Structured Data 11. Combining Data into Structures 11.2.
Topic 4 Data Structures Program Development and Design Using C++, Third Edition.
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
LESSON 06.
Structure, Unions, typedef and enumeration
Programming Structures.
Lecture 9 Structure 1. Concepts of structure Pointers of structures
C Structures, Unions, and Enumerations
C Structures, Unions, Bit Manipulations and Enumerations
Derived types.
Chapter 1: Introduction to Data Structures(8M)
C Structures, Unions, Bit Manipulations and Enumerations
Structures In C Programming By Rajanikanth B.
Standard Version of Starting Out with C++, 4th Edition
Structures Chapter 4.
Presentation transcript:

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

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

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

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

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

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

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 = F; //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 $ Press any key to continue...

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

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, }; //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...

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

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

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

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

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

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

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, }, { 45, 360, } }; 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]

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.

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;

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

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

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

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

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