Chapter 7 (Part I) - User Defined Datatypes
Chapter 7 (Part I) - User Defined Datatypes
Computer Programming
Chapter 7
User Defined Data types
(Structure in C++ )
Chere L. (M.Tech)
Lecturer, SWEG, AASTU
1
Outline
▪ Introduction to User defined Data type
▪ Defining structure (with tag and without tag)
▪ Declaring structure variable
▪ Initializing structure elements
▪ Accessing structure elements
▪ Nested structure
Defining structure within structure
Structure variable within other structure definition
▪ Array of structure
▪ Structure pointer
▪ Structure with function
Structure variable as parameter
Structure as a return type
Chapter 7 2
Outline
▪ Other User defined Data types
Type definition (typedef)
Enumerated types (enum)
Anonymous unions (union)
▪ Class and Object as user defined data type
Class and Object Basics
Class and Object Creation
Chapter 7 3
(1) User Defined Data Types
CONTENTS
Recalling the categories of Data Types
User Defined DT
Structure Basics
Nested Structures
Array of Structures
Struct manipulation
Structure Pointer
Chapter 7 4
(1) User Defined Data Types
CONTENTS
Why User Defined Data Types?
User Defined DT
1. Flexibility
Structure Basics
• They provide us the ability to create a data structure
Nested Structures as per our requirements and needs.
Array of Structures
2. Reusability
Struct manipulation
• Once defined, these data types can be reused within
Structure Pointer many definitions, saving coding time.
Structure & Function
3. Encapsulation
Other User Defined DT
• In C++/Java/Python the variables and data values
Class and Objects stored in User Defined Data types are hidden from
other classes as per their accessibility declaration i.e.
public, private, protected. The data values remain
hidden and safe. Chapter 7 5
(2) Structure Basics
CONTENTS
2.1 Structure
User Defined DT A Structure is a collection of related data items,
Structure Basics possibly of different types.
Examples:
Nested Structures
Student record:
Array of Structures
student id, name, major, gender, start year, …
Struct manipulation Bank account:
Structure Pointer account number, name, currency, balance, …
Structure & Function Address book:
name, address, telephone number, …
Other User Defined DT
Chapter 7 6
(2) Structure Basics (Cont’d)
CONTENTS
2.2 C++ Structure
User Defined DT Structure is a user defined data type that is an
Structure Basics
aggregate container
A simple variable can store only one value at a time of
Nested Structures
single type (atomic)
Array of Structures A structure is can be considered as a collection of those
Struct manipulation simple variables.
i.e. It used to join simple variables together to form a bit
Structure Pointer
complex variables.
Structure & Function In other words, it contains other data types, which are
Other User Defined DT
grouped together into a single user-defined type.
Unlike arrays (homogeneous), structures can store
Class and Objects
variables of many different types (heterogeneous)
Structures are used when it makes sense to associate
two or more data variables.
Chapter 7 7
(2) Structure Basics (Cont’d)
CONTENTS
2.3 Structure Declaration
User Defined DT Programmer can define a new data type that may
Structure Basics
contain different types of data with the help of
structures.
Nested Structures
A structure is declared by using C++ keyword struct
Array of Structures
Syntax:
Struct manipulation struct structName{
Structure Pointer
dataType1 identifier1;
Structure & Function
dataType2 identifier2;
Other User Defined DT
:
Class and Objects
dateTypeN identifierN;
}; Chapter 7 8
(2) Structure Basics (Cont’d)
CONTENTS
Descriptions
User Defined DT The structure name also called structure tag and
Structure Basics used as the name of newly created user defined DT.
Nested Structures
Individual components of a structure type are called
members (or fields).
Array of Structures
The structure members are defined with their data-type
Struct manipulation (simple, array or struct type) inside the opening and
closing curly braces..
Structure Pointer
Must have unique names within the structure definition
Structure & Function
The closing brace is ended with a semicolon.
Other User Defined DT
Structure can be declared inside or outside main
Class and Objects function/any other functions
Complex data structures can be formed by defining
arrays of structs.
Chapter 7 9
(2) Structure Basics (Cont’d)
CONTENTS
The structure declaration tells the compiler about
User Defined DT the details of the structure.
It tells how the structure is organized
Structure Basics
It specifies what members the structure will
Nested Structures
have.
Array of Structures
However, memory is not allocated.
Struct manipulation
Unlike the definition of a simple variable,
Structure Pointer Structure definition don’t reserve memory
Structure & Function
Chapter 7 10
(2) Structure Basics (Cont’d)
CONTENTS
More Examples
User Defined DT
struct BankAccount{
Structure Basics char Name[15]; The “BankAcount”
int AcountNo[10];
double balance; structure has simple,
Nested Structures
Date Birthday; array and structure
Array of Structures }; types as members.
Struct manipulation
struct StudentRecord{
Structure Pointer char Name[15];
int Id; The “StudentRecord”
Structure & Function char Dept[5]; structure has 4
char Gender;
members.
Other User Defined DT };
Class and Objects
Exercise:
Write a structure specification that includes three members
student id, age, and mark. Call this structure student
Chapter 7 11
(2) Structure Basics (Cont’d)
CONTENTS
2.4 Structure Definition
User Defined DT
By defining a structure you create a new data type.
Structure Basics
Once a structure is declared, you can create
Nested Structures
variables of the new type as follow
Array of Structures
<struct> <struct tag> <identifier>;
Struct manipulation
or <struct tag> <identifier>;
Structure Pointer
variable to
keyword struct hold one
struct tag student record
Chapter 7 12
(2) Structure Basics (Cont’d)
CONTENTS
Descriptions
User Defined DT The structure variable can be defined after the
Structure Basics declaration or the time of structure declaration.
Nested Structures
The process of defining a structure variable is same
as defining a variable of basic types such as int, char
Array of Structures
The definition of the structure variable
Struct manipulation
Tells the compiler to allocate memory space for the
Structure Pointer variable.
Structure & Function The compiler automatically allocates sufficient
Other User Defined DT
memory according to the elements of the structure.
The memory occupied by the structure variable is
Class and Objects
equal to the sum of the memory occupied by each
member of the structure
Chapter 7 13
(2) Structure Basics (Cont’d)
CONTENTS
User Defined DT
Structure Basics
Nested Structures
Array of Structures
Struct manipulation
Structure Pointer
Other User Defined DT • The structure variable p1 will occupy bytes in the memory
as follows.
Class and Objects
int modelnumber (4 bytes) + int partnumber (4 bytes) +
float cost (4 bytes)
• Total number of bytes p1 contains in memory is 12 bytes
Chapter 7 14
(2) Structure Basics (Cont’d)
CONTENTS
2.5 Accessing Structure Members
User Defined DT Once a structure variable has been defined, its members
Structure Basics
can be accessed using the dot operator (also called
member access operator)
Nested Structures
The dot operator placed between a struct variable and a
Array of Structures member variable name for that struct type.
Struct manipulation The name of the structure variable is written on the left
side of the dot operator where as the name of member
Structure Pointer
variable is written on right side of the dot operator.
Structure & Function
Syntax:
Other User Defined DT StructureVariable . MemberVariable;
Class and Objects
Array of Structures
part2
Struct manipulation part1
Input/output
Structure Pointer
Chapter 7 16
(2) Structure Basics (Cont’d)
CONTENTS
Program Examples //give values to structure members
part1.modelnum = 6244;
User Defined DT #include <iostream.h> part1.partnum = 373;
Using namespace std part1.cost = 217.55F;
Structure Basics
Nested Structures
Example: Consider the previous part struct declration
part tyre = { 2011, 34, 13.50};
Array of Structures
Chapter 7 20
(2) Structure Basics (Cont’d)
CONTENTS
Structure Declaration and Definition without tag
User Defined DT Structure without tag and definition
Structure Basics struct {
char name[20];
Nested Structures This kind of structure
int age;
declaration is useless
Array of Structures Date dateOfBirth;
};
Struct manipulation
Structure Pointer
Structure without tag but with definition
Structure & Function
Chapter 7 22
(2) Structure Basics (Cont’d)
CONTENTS
Accessing array elements
User Defined DT The array stored in a structure can be accessed by using the
following
Structure Basics
Name of Structure Variable - in which an array is defined
1.
Nested Structures Dot Operator - used to refer the array.
2.
Name of Array
3.
Array of Structures
Index of desired element - used to access the individual
4.
Struct manipulation element of the array.
Example
Structure Pointer
int main(){
# include <iostream.h>
usman.roll_number = 101;
Structure & Function struct studen{
for(int i = 0; i < 5 ; i++)
int roll_number;
Other User Defined DT usman.marks[i] = 1 + rand() % 100
int marks[5];
cout<<endl;
Class and Objects };
for(int i = 0; i < 5 ; i++)
cout << usman.marks[i] << endl;
student usman;
return 0;
}
Chapter 7 23
(2) Structure Basics (Cont’d)
CONTENTS
Initializing array elements
User Defined DT The structure that contains an array as member variable can be
initialized in the same the same way as initializing a simple
Structure Basics structure variable.
Nested Structures The values are written in braces and each value is separated by
comma.
Array of Structures
additionally, the values for the member array are written in
Struct manipulation nested braces, in proper order.
Structure Pointer Example
int main() {
# include <iostream.h>
student usman = {101,
Structure & Function Using namespace std;
{60,75,85,52,53}};
Other User Defined DT
struct studen{
for(int i = 0; i < 5 ; i++) {
Class and Objects int roll_number;
cout << "Marks: " << usman.marks[i]
int marks[5];
cout<< endl;}
};
return 0;
}
Chapter 7 24
(3) Nested Structure
CONTENTS
3.1 Nested Structure
User Defined DT Refers to a structure within a structure
A nested structure is created when the member of a
Structure Basics
structure is itself a structure or
Nested Structures When the structure definition placed within an other
structure definition
Array of Structures
Example struct Student{
Struct manipulation char name[20];
struct Date{ int age;
Structure Pointer
int date, month, year;
Date dateOfBirth;
};
Structure & Function };
Other User Defined DT In the example above the structure Date contains simple
member variables day, month, year of data type int.
Class and Objects
Second structure Student contains three member variables.
The first two members are of basic data type, but the third
member of Structure Student is itself a structure variable.
Chapter 7 25
(3) Nested Structure (Cont’d)
CONTENTS
3.2 Accessing Members of Nested Structure
User Defined DT The member variable of nested structure can be accessed using
multiple dot operators.
Structure Basics
The first dot operator refers the member variable of outer
Nested Structures structure
The second dot operator refers the inner structure and so on.
Array of Structures
Example: consider the declaration on the previous Slide
Struct manipulation We have defined Nested Structure Date & Student
Structure Pointer
Let’s declare a variable of Student struct as follow
Student sweg; // sweg further contains a structure
Structure & Function
sweg.dateOfBirth.year = 1940;
Chapter 7 27
(3) Nested Structure (Cont’d)
CONTENTS
3.3 Defining Structure in Structure (not good practice)
User Defined DT struct moment{
int evnetID;
Structure Basics char eventVenue[20];
struct date{
Nested Structures
int day, month, year;
Array of Structures }theDate;
Struct manipulation
struct time{
Structure Pointer int second, minute, hour;
} theTime;
Structure & Function
};
Other User Defined DT
How to access an elements of this structure?
Class and Objects
Moment event;
event.theDate.day = 25;
event.theTime.hour = 4;
Chapter 7 28
(3) Nested Structure (Cont’d)
CONTENTS Nested structure - Complete Program
User Defined DT #include <iostream.h>
Using namespace std
Structure Basics
struct Date{ cout << "Student Data\n" << endl;
int day, month, year; cout<< “Roll Number: " <<sweg.rollNumber;
Nested Structures
}; cout << ", Age: " <<sweg.age;
Array of Structures struct Student{ cout<< "\nDateOfBirth: “
<<sweg.dateOfBirth.day << " / “;
int rollNumber, age;
Struct manipulation <<sweg.dateOfBirth.month <<" / “;
Date dateOfBirth; cout<< sweg.dateOfBirth.year << endl;
Structure Pointer
}; return 0;
}
Structure & Function int main(){
Student sweg;
Other User Defined DT
sweg .rollNumber = 123; Student Data
Structure Basics
Nested Structures
Array of Structures
Struct manipulation
Structure Pointer
}
Chapter 7 30
(4) Array of Structure
CONTENTS 4.1 Array of Structure Definition
User Defined DT An array can be of user-defined type such as a structure.
Structure Basics An array of structure is a type of array in which each
element contains a complete structure.
Nested Structures
It can be used to store many records
Array of Structures Example
struct Book{
Struct manipulation
int BookID;
Structure Pointer int Pages;
Structure & Function
float Price;
}b[3];
Other User Defined DT
The above example declares a structure Book and defines
Class and Objects an array of structure, b[3] of structure Book.
The array structure b[3] can store the records of three
books.
Chapter 7 31
(4) Array of Structure (Cont’d)
CONTENTS 4.2 Manipulating array of Structure
User Defined DT Like simple array, structure array is accessed by using its index.
Structure Basics
The structure element is accessed by using dot operator.
Example: Consider the previous declaration of book struct
Nested Structures
Array of Structures
Struct manipulation
Structure Pointer
b[0].BookID= 154;
b[0].Pages = 1036; Book b[3];
Structure & Function
b[0].Price = 425;
Other User Defined DT
And simply…
Class and Objects cout << “Book ID: ” << b[0].BookID << endl;
cout << “Book Pages: ” << b[0].Pages << endl;
cout << “Book Price: ” << b[0].Price << endl;
Chapter 7 32
(4) Array of Structure (Cont’d)
CONTENTS 4.3 Initializing array of Structure
User Defined DT An array of structures can be initialized at the time of
declaration by writing the values in braces.
Structure Basics
The values for each element of the array are written in separate
Nested Structures inner braces.
Example
Array of Structures struct Book{int BookID, Pages; float Price; };
Class and Objects Instead you must write code which will compare or
Input/output individual the structs elements
Chapter 7 35
(5) Structure Pointer
CONTENTS
User Defined DT
Structure Basics
Structure Pointer
Chapter 7 36
(6) Structure with Function
CONTENTS Both structure variables and structure elements can be passed to
a function and returned in a similar way as normal arguments.
User Defined DT
Moreover, structure passing can be achieved both by call by
Structure Basics value and call by reference method.
Nested Structures Example 1: Passing Structure Elements to Functions
Array of Structures #include <iostream>
int main() {
using namespace std;
Struct manipulation Student S1;
struct Student {
cout<<"Enter student marks:\n";
Structure Pointer char id[10];
for(int i = 0; i<5; i++){
float mark[5];
cout<<"Enter "<<i+1<<" Mark: ";
Structure & Function };
cin>>S1.mark[i];
float avgMark(float sMark[]){
Other User Defined DT
}
float total = 0;
cout<<"Average score: “
for(int i = 0; i<5; i++)
Class and Objects <<avgMark(S1.mark)<<endl;
total += sMark[i];
return 0;
return (total/5);
}
}
Chapter 7 37
(6) Structure with Function (Cont’d)
CONTENTS
Example 2: Passing Structure variable by Value and return
User Defined DT
structure variable (entire structure).
Chapter 7 40
(6) Structure with Function (Cont’d)
CONTENTS void getData(Person &p) {
cout << "Enter ID: "; cin >> p.id;
User Defined DT
cout << "Enter Full name: "; cin.get(p.name, 50);
Structure Basics cout << "Enter age: "; cin >> p.age;
cout << "Enter salary: "; cin >> p.salary;
Nested Structures Example 3
return p;
Array of Structures (Cont.… ) }
Struct manipulation
Structure Pointer
void Display(Employee E){
cout << "\n\nEmployee Id : " << E.Id;
Structure & Function
cout << "\nEmployee Name : " << E.Name;
Other User Defined DT cout << "\nEmployee Age : " << E.Age;
cout << "\nEmployee Salary : " << E.Salary;
Class and Objects
}
Chapter 7 41
(6) Structure with Function (Cont’d)
CONTENTS
Example 4
User Defined DT #include <iostream>
Structure Basics using namespace std;
Nested Structures
struct Pixels{
Array of Structures string color;
Struct manipulation int style;
};
Structure Pointer
Chapter 7 42
(6) Structure with Function (Cont’d)
CONTENTS
Example 4 (cont. . . )
User Defined DT Pixels readPoint(){
Structure Basics
Pixels myPoint;
cout<<"What is the pixel color: "; cin>>myPoint.color;
Nested Structures
cout<<"What is the pixel style: "; cin>>myPoint.style;
Array of Structures return myPoint;
Struct manipulation
}
A phone number, such as (212) 767-8900, can be thought of as having three parts:
the area code (212), the exchange (767), and the number (8900). Write a program
that uses a structure to store these three parts of a phone number separately. Call
the structure phone.
Create two structure variables of type phone. Initialize one, and have the
user input a number for the other one. Then display both numbers.
Modify the program you design for Ex. 1 so that the program asks names of 10
persons and also phone numbers. Use the phone structure in the previous exercise
and create another structure that includes names of persons and phone structure.
Chapter 7 45
Practical Exercise
3. [structure with function]
Declare a structure to represent a complex number (a number having a real part
and imaginary part). Write C++ functions to add, subtract, multiply and divide two
complex numbers.
4. [array of structure]
(Financial) Write a C++program that uses a structure for storing a stock name, its
estimated earnings per share, and its estimated price-to-earnings ratio. Have the
program prompt the user to enter these items for five different stocks, each time
using the same structure to store the entered data. When data has been entered
for a particular stock, have the program compute and display the anticipated
stock price based on the entered earnings and price-per-earnings values. For
example, if a user enters the data XYZ, 1.56, 12, the anticipated price for a share
of XYZ stock is (1.56) × (12) = $18.72.
Chapter 7 46
Practical Exercise
5. [structure array with function]
Given a structure a specification to store the details of 10 students (rollno, name,
marks in five subject, BoD which it’s type is Date struct), write a program to input
each students detail using function and perform the following;
a) Compute average score for each student and print the students’ details in
tabular format along with their scores
b) Determine and print students details who scored average mark below 50
Chapter 7 48
MCQ
1. Which of keyword is used for structure definition?
a) Structure c) Struct
b) Struct_def d) def_struct e) None of the above
2. An aggregate data type that constructed using other types, is called?
a) Structure c) Class
b) Function d) Pointer e) Elements
3. Which of the following statements is true about C++ structs?
a) All members must be of the same type.
b) Members can be initialized on one line of code.
c) Each member must be passed individually.
d) Functions cannot accept structs as parameters.
4. Structure within a structure is called......
a) Self-Referential Structure c) Nested Structure
b) Array of Structure d) Structure of Structure
Chapter 7 49
MCQ
5. Which of the following cannot be a structure member?
a) another structure c) array
b) Function d) None
6. Which of the following is true for accessing an element of a structure
a) struct.element
b) structure_tag.element
c) structure_variable.element
d) structure_tag.structure_variable
7. What will happen when the structure is declared?
a) it will not allocate any memory
b) it will allocate the memory
c) it will be declared and initialized
d) it will be declared
8. Which of the following is a properly defined structure?
a) struct {int a;} c) struct a_struct {int a;}
b) struct a_struct int a; d) struct a_struct {int a;};
Chapter 7 50
Short answer
1. Why struct keyword is used during structure definition in C?
2. What is preventing the below structure declaration from compiling?
struct Employee { int id; float wage; }
3. What is the output of the following codes?
(3a) (3b) struct MyBox{ int length, breadth, height; };
int main(){ void dimension (MyBox M){
struct student{ cout << M.length << "x" << M.breadth << "x";
int no; cout << M.height << endl;
char name[20]; }
}; int main (){
struct student s; MyBox B1 = {10, 15, 5}, B2, B3;
s.no = 8; ++B1.height; dimension(B1);
cout<< s.no; B3 = B1; ++B3.length;
} B3.breadth++; dimension(B3);
B2 = B3; B2.height += 5;
B2.length--; dimension(B2);
Chapterreturn
7 0; } 51
Reading Resources/Materials
Chapter 10:
✔ Walter Savitch; Problem Solving With C++ [10th edition],
University of California, San Diego, 2018
Chapter 8:
✔ Bjarne Stroustrup;The C++ Programming Language [4th
Edition], Pearson Education, Inc , 2013
Chapter 7 52
Thank You
For Your Attention!!
Chapter 7 53