0% found this document useful (0 votes)
61 views

Chapter 7 (Part I) - User Defined Datatypes

struct Student { int id; int age; int mark; };

Uploaded by

samuel noah
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views

Chapter 7 (Part I) - User Defined Datatypes

struct Student { int id; int age; int mark; };

Uploaded by

samuel noah
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

Fundamentals of

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

Structure & Function

Other User Defined DT

Class and Objects

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

Class and Objects


 In database applications, structures are called records.

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

Other User Defined DT  Example:


Class and Objects

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

Structure & Function  Example: Consider the previous StudentRecord strcut


Other User Defined DT
definition
struct StudentRecord currentStudent;
Class and Objects

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

Structure & Function

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

 Example: Part p1;


P1.modelNumber;
Chapter 7 15
(2) Structure Basics (Cont’d)
CONTENTS
More Examples
User Defined DT
Structure (e.g. part )
Structure Basics
part part2
Nested Structures part part1

Array of Structures
part2
Struct manipulation part1
Input/output
Structure Pointer

Structure & Function Store values in structure cin>>part2.modelnumber;


elements cin>>part2.partnumber;
Other User Defined DT cin>>part2.cost;
part1.modelnumber = 2001
Class and Objects part1.partnumber = 11 cout<<part2.modelnumber;
part1.cost = 100 cout<<part2.partnumber;
cout<<part2.cost;

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

//display structure members


Nested Structures /***Structure definition***/
cout<<"Model: "<< part1.modelnum;
Array of Structures
//declare a structure cout<<"\nPart: " << part1.partnum;
struct part{ cout<<"\nCosts $"<<part1.cost << endl;
Struct manipulation return 0;
int modelnum;
}
Structure Pointer int partnum;
float cost;
Structure & Function Exercise:
}; • Declare a structure with student
Other User Defined DT
/*** End of Structure ***/ attribute (id, name, testMark,
Class and Objects final mark) members. Write a
int main(){
program to input data, compute
//define a structure variable sum of the mark and print the
part part1; records of the student.
Chapter 7 17
(2) Structure Basics (Cont’d)
CONTENTS
2.6 Initializing Structure Variable
User Defined DT  The process of assigning values to structure elements
Structure Basics
during structure declaration is called Initialization of
Structure variables.
Nested Structures
 The structure members can be initialized when the
Array of Structures structure variable is defined.
Struct manipulation  The syntax for initializing structs is similar to the syntax
for arrays where the declaration of structure variable is
Structure Pointer
specified on the left side of assignment operator and the
Structure & Function list of values for initialization are written on the right
Other User Defined DT
side of assignment operator surrounded by the curly
braces.
Class and Objects
 The values are written in the same sequence in which
they are specified in structure declaration.
 Each value is separated by comma.
Chapter 7 18
(2) Structure Basics (Cont’d)
CONTENTS
Syntax
User Defined DT structureName Identifier = {val1, val2, … , valN} ;
Structure Basics

Nested Structures
Example: Consider the previous part struct declration
part tyre = { 2011, 34, 13.50};
Array of Structures

Struct manipulation struct part


{
Structure Pointer int modelnumber;
int partnumber;
Structure & Function
float cost;
Other User Defined DT };

Class and Objects


Note:
 Both the structure variable and initialization can be performed at
the time of structure declaration. **Checkout on next slide.
Chapter 7 19
(2) Structure Basics (Cont’d)
CONTENTS Program Examples: Initialization of structure variable
User Defined DT #include <iostream.h> int main(){
using namespace std //initialize structure variable
Structure Basics
part part2 = { 2011, 34, 13.50 };
Nested Structures
//specify a structure cout << "Model: \tPart Number\t Price";
Array of Structures struct part{ cout<<"\n"<< part1.modelnum<<"\t\t“;
int modelnum; cout<< part1.partnum<< "\t$“;
Struct manipulation cout<< part1.cost<<endl;
int partnum;
cout << "\n"<< part1.modelnum<<"\t\t“;
Structure Pointer float cost; cout<< part1.partnum<< "\t$“;
Structure & Function } part1 = {2021, 43, 31.5}; cout<< part1.cost<<endl;

Other User Defined DT return 0;


}
Class and Objects //definition + initialization
//at the time of declaration

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

Other User Defined DT


struct {
This kind of structure declaration
char name[20];
is not recommendable because
Class and Objects int age; the you cannot define a
Date dateOfBirth; structure of this type some
}Stud1, Stud2; where else
Chapter 7 21
(2) Structure Basics (Cont’d)
CONTENTS
CONTENTS
2.7 Array as Member of Structure
User Defined DT
User Defined DT  As discussed earlier a structure may consist of different types of
Structure Basics
data and the member variables can be simple data types such
Structure Basics as int, char and float or can be complex like arrays.
Nested Structures  Example: array as a member of structure
Nested Structures
Array of Structures
Array of Structures
struct Student{
int Roll_number;
Struct manipulation
Struct manipulation int Marks[5];
Structure Pointer
Structure Pointer };
 In the above example, the first member is a simple variable of
Structure & Function
Structure & Function type int where as he second member is an array of integers
Other User Defined DT
Other User Defined DT
that can be used to store the marks of five subjects.
Class and Objects  Student sweg_2012_Batch;
Class and Objects

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

Other User Defined DT


 Let’s assign values statically…
sweg.name = "Abebe Solomon";
Class and Objects sweg.age = 25;
sweg.dateOfBirth.day = 23;
sweg.dateOfBirth.month = 3;
sweg.dateOfBirth.year = 1940; 26
Chapter 7
(3) Nested Structure (Cont’d)
CONTENTS  In the above example the Student struct nested
User Defined DT
structure that contains another structure variable
dateOfBirth of type Date as its member.
Structure Basics
 As a result, the first statement uses one dot operator as
Nested Structures it refers to simple member variable of the structure.
 The last three statements uses two dot operators as
Array of Structures
they refer to the members of the nested structure
Struct manipulation variables.
Student (Outer Structure)
Structure Pointer (name, age, dateOfBirth)

Structure & Function


Date (inner Structure)
(day, month, year)
Other User Defined DT

Class and Objects

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

Class and Objects


sweg.age = 25; Roll Number: 123, Age: 25
sweg.dateOfBirth.day = 23; DateOfBirth: 23 / 3 / 1940
Press any key to continue . . .
sweg.dateOfBirth.month = 3;
sweg.dateOfBirth.year = 1940;
Chapter 7 29
(3) Nested Structure (Cont’d)
CONTENTS
Nested structure - A Drawing Example
User Defined DT

Structure Basics

Nested Structures

Array of Structures

Struct manipulation

Structure Pointer

Structure & Function

Other User Defined DT

Class and Objects

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

Struct manipulation b[0]


Book b[3] = { { 11, 125, 50.0},
b[1]
Structure Pointer { 31, 480, 185.75},
{ 45, 360, 145.50} }; b[2]
Structure & Function  This example declares an array of structure and initializes it.
Other User Defined DT  The values are written in braces with the help of nested braces,
separated by commas, to refer each book in the Structure
Class and Objects Array.
 Each inner pair of braces is used to initialize one element of the
array.
Chapter 7 33
(5) Manipulation of Structure
CONTENTS 4.1 Structure aggregate assignment operation
User Defined DT  One structure variable can be assigned to another structure
variable only if both are of same type.
Structure Basics
 Example:
Nested Structures #include <iostream.h>
struct part{
Array of Structures int modelnum, partnum;
float cost;
Struct manipulation };
int main(){
Structure Pointer part part1 = { 2011, 34, 13.50 };
part part2 = part1; // Assignment Statement
Structure & Function
cout << "Model: " << part2.modelnumber;
Other User Defined DT cout << "\nPart: " << part2.partnumber;
cout << "\nCosts: $" << part2.cost << endl;
Class and Objects return 0; }
 Note: like the above example a structure variable can be initialized by
assigning another structure variable to it by using assignment operator
Chapter 7 34
(5) Manipulation of Structure (Cont’d)
CONTENTS 4.2 Structure comparison
User Defined DT  Two structure variable cannot compared using relation
operators like using == or !=
Structure Basics
 Structure doesn’t support aggregate comparison as well
Nested Structures as aggregate input/output
Array of Structures struct part P1, P2;
if (P1 == p2) //invalid
Struct manipulation

Structure Pointer  Trying to perform aggregate comparison or Input/output


should cause a syntax error
Structure & Function
 The same problems as arrays
Other User Defined DT

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

Nested Structures Will discussed In the next


Array of Structures
Chapter
Struct manipulation

Structure Pointer

Structure & Function

Other User Defined DT

Class and Objects

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

Structure Basics #include <iostream>


Nested Structures using namespace std;
int main() {
Array of Structures Person p1, P2;
struct Person {
Struct manipulation char name[50]; p2 = getData(p1);
Structure Pointer int age; displayData(p2);
float salary; return 0;
Structure & Function
}; }
Other User Defined DT

Class and Objects Person getData();


void displayData(Person);
Chapter 7 38
(6) Structure with Function (Cont’d)
CONTENTS Person getData(Person p) {
cout << "Enter Full name: ";
User Defined DT
cin.get(p.name, 50);
Structure Basics cout << "Enter age: ";
cin >> p.age;
Nested Structures
Example 2 cout << "Enter salary: ";
Array of Structures cin >> p.salary;
(Cont.… )
Struct manipulation
return p;
}
Structure Pointer
void displayData(Person p) {
Structure & Function
cout << "\nDisplaying Information.\n" ;
Other User Defined DT cout << "Name: " << p.name << endl;
Class and Objects cout <<"Age: " << p.age << endl;
cout << "Salary: " << p.salary;
}
Chapter 7 39
(6) Structure with Function (Cont’d)
CONTENTS
 Example 3: Passing Structure variable by reference
User Defined DT
#include <iostream>
Structure Basics using namespace std;
int main() {
Nested Structures Employee Emp =
struct Employee {
Array of Structures {1,"Kumar",29,45000};
int Id;
Struct manipulation char Name[25];
Display(Emp);
Structure Pointer int Age;
getData(EMp);
long Salary;
Structure & Function Display(Emp);
};
Other User Defined DT
return 0;
Class and Objects void Display(Employee);
}
Void getData(Employee &);

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

Structure & Function


void showPoint(Pixels P, int n){
Other User Defined DT cout<<"\n\nThe "<<n<<" point Color & STyle\n“;
Class and Objects cout<<P.color<<"\t"<<P.style << endl;
}

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
}

Structure Pointer int main(){


Structure & Function
Pixels Point1 = readPoint();
showPoint(Point1, 1);
Other User Defined DT
Pixels Point2 = Point1; Point1.color+= 2;
Class and Objects showPoint(Point2, 2); showPoint(Point1, 1);
return 0;
} Chapter 7 43
Summary
 Structure Declaration  Variable structure elements
 Array structure elements
 Structure Definition
 Structure variable
 Accessing Structure Elements
 Initialize Structure Variable  Initializing simple variable member
 Array of Structure  Initializing array elements
 Initializing array structure
 Structure Manipulation
 Nested structure
 Structure declaration within other struct
 Structure with function
 Using structure variable as a member

 Passing structure variable


 Passing
Chapter structure
7 element(s) 44
Practical Exercise
1. [structure Declaration, Definition, initialization and accessing elements]

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.

2. [Nested & array of structure]

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

6. [structure array with function]


In two dimensions, a vector is a pair of numbers representing directed arrows in a
plane, as shown by vectors V1 and V2 in Figure on the next slide. Two-dimensional
mathematical vectors can be written in the form (a,b), where a and b are called the
x and y components of the vector. Using this information, write a C++program that
defines an array of two mathematical vector structures; each structure consists of
two double-precision components, a and b. Your program should permit a user to
enter two vectors, call two functions that return the sum and difference of the
entered vectors, and display the results calculated by these functions.
Chapter 7 47
Practical Exercise
Two dimensions Vector Plane

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

You might also like