SlideShare a Scribd company logo
1 of 57
Records (structs)
CS103- Computer Programming
2
Structures
• A Structure is a collection of related data items, possibly of
different types.
• A structure type in C++ is called struct.
• A struct is heterogeneous in that it can be composed of
data of different types.
• In contrast, array is homogeneous since it can contain only
data of the same type.
3
Structures
• Structures hold data that belong together.
• Examples:
– Student record: student id, name, major, gender, start year, …
– Bank account: account number, name, currency, balance, …
– Address book: name, address, telephone number, …
• In database applications, structures are called records.
4
Structures
• Individual components of a struct type are called members
(or fields).
• Members can be of different types (simple, array or struct).
• A struct is named as a whole while individual members are
named using field identifiers.
• Complex data structures can be formed by defining arrays
of structs.
5
struct basics
• Definition of a structure:
struct <struct-type>{
<type> <identifier_list>;
<type> <identifier_list>;
...
} ;
• Example:
struct Date {
int day;
int month;
int year;
} ;
The “Date” structure
has 3 members,
day, month & year.
Each identifier
defines a member
of the structure.
6
struct examples
• Example:
struct StudentInfo{
int Id;
int age;
char Gender;
double CGA;
};
• Example:
struct StudentGrade{
char Name[15];
char Course[9];
int Lab[5];
int Homework[3];
int Exam[2];
};
The “StudentGrade”
structure has 5
members of
different array types.
The “StudentInfo”
structure has 4 members
of different types.
7
struct examples
• Example:
struct BankAccount{
char Name[15];
int AcountNo[10];
double balance;
Date Birthday;
};
• Example:
struct StudentRecord{
char Name[15];
int Id;
char Dept[5];
char Gender;
};
The “StudentRecord”
structure has 4
members.
The “BankAcount”
structure has simple,
array and structure
types as members.
8
struct basics
• Declaration of a variable of struct type:
<struct-type> <identifier_list>;
• Example:
StudentRecord Student1, Student2;
Student1 and Student2 are variables of
StudentRecord type.
Student1 Student2
Name
Id Gender
Dept
Name
Id Gender
Dept
9
Chan Tai Man
12345 M
COMP
Ex. 1: struct basics
• The members of a struct type variable
are accessed with the dot (.) operator:
<struct-variable>.<member_name>;
• Example:
strcpy(Student1.Name, "Chan Tai Man");
Student1.Id = 12345;
strcpy(Student1.Dept, "COMP");
Student1.gender = 'M';
cout << "The student is ";
switch (Student1.gender){
case 'F': cout << "Ms. "; break;
case 'M': cout << "Mr. "; break;
}
cout << Student1.Name << endl;
Student1
Name
Id Gender
Dept
Records (structs)
• struct: collection of a fixed number of components
(members), accessed by name
– Members may be of different types
• Syntax:
10
Records (structs) (cont'd.)
• A struct is a definition, not a declaration
11
Records (structs) (cont'd.)
12
Accessing struct Members
• The syntax for accessing a struct member is:
• The dot (.) is an operator, called the member access
operator
13
Accessing struct Members (cont'd.)
• To initialize the members of newStudent:
newStudent.GPA = 0.0;
newStudent.firstName = "John";
newStudent.lastName = "Brown";
14
Accessing struct Members (cont'd.)
• More examples:
cin >> newStudent.firstName;
cin >> newStudent.testScore >>
newStudent.programmingScore;
score = (newStudent.testScore +
newStudent.programmingScore) / 2;
15
Accessing struct Members (cont'd.)
if (score >= 90)
newStudent.courseGrade = 'A';
else if (score >= 80)
newStudent.courseGrade = 'B';
else if (score >= 70)
newStudent.courseGrade = 'C';
else if (score >= 60)
newStudent.courseGrade = 'D';
else
newStudent.courseGrade = 'F';
16
Example Movie Struct
// example about structures
#include <iostream>
#include <string>
using namespace std;
struct movies_t {
string title;
int year;
} mine, yours;
void printmovie (movies_t movie);
int main ()
{
string mystr;
mine.title = "2001 A Space
Odyssey";
mine.year = 1968;
cout << "Enter title: ";
getline (cin,yours.title);
cout << "Enter year: ";
getline (cin,mystr);
cin>> yours.year;
cout << "My favorite movie is:n ";
printmovie (mine);
cout << "And yours is:n ";
printmovie (yours);
return 0;
}
void printmovie (movies_t movie)
{
cout << movie.title;
cout << " (" << movie.year <<
")n";
}
17
Example Conti…
Enter title: Alien
Enter year: 1979
My favorite movie is:
2001 A Space Odyssey (1968)
And yours is:
Alien (1979)
18
Assignment
• Value of one struct variable can be assigned to another
struct variable of the same type using an assignment
statement
• The statement:
student = newStudent;
copies the contents of newStudent into student
19
Assignment (cont'd.)
• The assignment statement:
student = newStudent;
is equivalent to the following
statements:
student.firstName = newStudent.firstName;
student.lastName = newStudent.lastName;
student.courseGrade = newStudent.courseGrade;
student.testScore = newStudent.testScore;
student.programmingScore =
newStudent.programmingScore;
student.GPA = newStudent.GPA;
20
Comparison (Relational Operators)
• Compare struct variables member-
wise
– No aggregate relational operations allowed
• To compare the values of student and
newStudent:
21
Input/Output
• No aggregate input/output operations on a struct
variable
• Data in a struct variable must be read one member at a
time
• The contents of a struct variable must be written one
member at a time
22
struct Variables and Functions
• A struct variable can be passed as a parameter by
value or by reference
• A function can return a value of type struct
23
Arrays versus structs
24
Arrays in structs
• Two key items are associated with a list:
– Values (elements)
– Length of the list
• Define a struct containing both items:
25
Arrays in structs (cont'd.)
26
27
Arrays in structs (cont'd.)
structs in Arrays
28
29
structs in Arrays (cont’d.)
30
structs in Arrays (cont’d.)
structs within a struct
31
versus
Structs, and Pointer Variables
• You can declare pointers to other data types:
– student is an object of type studentType;
studentPtr is a pointer variable of type studentType
32
Structs, and Pointer Variables (cont'd.)
• To store address of student in studentPtr:
studentPtr = &student;
• To store 3.9 in component gpa of student:
(*studentPtr).gpa = 3.9;
– () used because dot operator has higher precedence than
dereferencing operator
– Alternative: use member access operator arrow (->)
33
Movie Example
// pointers to structures
#include <iostream>
#include <string>
using namespace std;
struct movies_t {
string title;
int year;
};
int main ()
{
string mystr;
movies_t amovie;
movies_t * pmovie;
pmovie = &amovie;
cout << "Enter title: ";
getline (cin, pmovie->title);
cout << "Enter year: ";
getline (cin, mystr);
(stringstream) mystr >>
pmovie->year;
cout << "nYou have
entered:n";
cout << pmovie->title;
cout << " (" << pmovie-
>year << ")n";
return 0;
}
34
Example Output…
Enter title: Invasion of the body snatchers
Enter year: 1978
You have entered:
Invasion of the body snatchers (1978)
35
Example …
pmovie->title is equivalent to (*pmovie).title
*pmovie.title is equivalent to *(pmovie.title)
36
Pointers & Structs
Expression What is evaluated Equivalent
a.b Member b of object a
a->b Member b of object pointed by a (*a).b
*a.b Value pointed by member b of object a *(a.b)
37
Structs & File Handling
• A file may be read record by record.
38
COMPLETE EXAMPLE OF POINT
39
Point Struct
with functions
struct Point{
int x;
int y;
void init(){
x=0;
y=0;
}
void init(int a, int b) // Overloaded
Function
{
x=a;
y=b;
}
void input(){
cout<<"nEnter value of X: ";
cin>>x;
cout<<"nEnter value of Y:";
cin>>y;
}
void print(){
cout<< "(" << x << "," << y <<")";
}
}; 40
void main()
{
Point p1,p2,p3={10,6},p4; //
All seem fine
p1.init();
p1.print();
p2.init(2,3);
p2.print();
p3.print();
p4.input();
p4.print();
}
//Output…
(0,0)
(2,3)
(10,6)
Enter value of X: 44
Enter value of Y:55
(44,55)
STUDENT’S HOME WORK
Sales Data Analysis
41
Programming Example: Sales Data Analysis
• A company has six salespeople
• Every month they go on road trips to sell the company’s
product
• At the end of each month, the total sales for each
salesperson, salesperson’s ID, and the month, are
recorded in a file
• At the end of each year, the manager of the company
asks for a report
42
Programming Example: Output Format
----------- Annual Sales Report -------------
ID QT1 QT2 QT3 QT4 Total
______________________________________________________________
12345 1892.00 0.00 494.00 322.00 2708.00
32214 343.00 892.00 9023.00 0.00 10258.00
23422 1395.00 1901.00 0.00 0.00 3296.00
57373 893.00 892.00 8834.00 0.00 10619.00
35864 2882.00 1221.00 0.00 1223.00 5326.00
54654 893.00 0.00 392.00 3420.00 4705.00
Total 8298.00 4906.00 18743.00 4965.00
Max Sale by SalesPerson: ID = 57373, Amount = $10619.00
Max Sale by Quarter: Quarter = 3, Amount = $18743.00
QT1 stands for quarter 1 (months 1 to 3), QT2 for quarter 2
(months 4 to 6), QT3 for quarter 3 (months 7 to 9), and QT4 for
quarter 4 (months 10 to 12)
43
Programming Example: Output Format (cont'd.)
• The salespeople IDs are stored in one file; sales data are
stored in another file
• The sales data is in the following form:
salesPersonID month saleAmount
.
.
.
• Sales data are not ordered
44
Programming Example: Input/Output
• Input: file containing each salesperson’s ID and a second
file containing the sales data
• Output: file containing annual sales report in the above
format
45
Programming Example: Problem Analysis
• Main components for each salesperson:
– ID
– Quarterly sales amount
– Total annual sales amount
• Use a struct to group the components
• Six people: array of size six
• Program requires total sales for each
quarter
– Use array of size four to store the data
46
Programming Example: Problem Analysis
(cont'd.)
47
Programming Example: Problem Analysis
(cont'd.)
• Read the salespeople IDs into the array
salesPersonList
• Initialize the quarterly sales and total sales for each
salesperson to 0
48
Programming Example: Problem Analysis
(cont'd.)
• For each entry in the file with the sales data:
– Read ID, month, sale amount for the month
– Search salesPersonList to locate the component
corresponding to this salesperson
– Determine the quarter corresponding to the month
– Update the sales for the quarter by adding the sale amount for
the month
49
Programming Example: Problem Analysis
(cont'd.)
• Once the sales data file is processed:
– Calculate the total sale by salesperson
– Calculate the total sale by quarter
– Print the report
50
Programming Example: Algorithm Design
• Translates into the following algorithm:
– Initialize the array salesPersonList
– Process the sales data
– Calculate the total sale by salesperson
– Calculate the total sale by quarter
– Print the report
– Calculate and print maximum sale by salesperson
– Calculate and print maximum sale by quarter
51
Programming Example: Main Algorithm
• Declare the variables
• Prompt user to enter name of file containing the
salesperson’s ID data
• Read the name of the input file
• Open the input file
• If input file does not exist, exit
• Initialize the array salesPersonList by calling the
function initialize
52
Programming Example: Main Algorithm (cont'd.)
• Close input file containing salesperson’s ID
• Prompt user to enter name of file containing sales data
• Read the name of the input file
• Open the input file
• If input file does not exist, exit
• Prompt user to enter name of output file
• Read the name of the output file
53
Programming Example: Main Algorithm (cont'd.)
• Open the output file
• Output data to two decimal places
• Process sales data
– Call the function getData
• Calculate the total sale by quarter by calling the function
saleByQuarter
• Calculate the total sale by salesperson by calling the
function totalSaleByPerson
54
Programming Example: Main Algorithm (cont'd.)
• Print the report in the tabular form; call the function
printReport
• Find and print the salesperson who produces the
maximum sales for the year by calling
maxSaleByPerson
• Find and print the quarter producing the maximum sale for
the year by calling maxSaleByQuarter
• Close files
55
Summary
• struct: collection of a fixed number of
components
• Components can be of different types
– Called members
– Accessed by name
• struct is a reserved word
• No memory is allocated for a struct
– Memory when variables are declared
56
Summary (cont'd.)
• Dot (.) operator: member access operator
– Used to access members of a struct
• The only built-in operations on a struct are the assignment
and member access
• Neither arithmetic nor relational operations are allowed on
structs
• struct can be passed by value or reference
• A function can return a value of type struct
• structs can be members of other structs
57

More Related Content

What's hot

Learning with classification and clustering, neural networks
Learning with classification and clustering, neural networksLearning with classification and clustering, neural networks
Learning with classification and clustering, neural networksShaun D'Souza
 
11. Objects and Classes
11. Objects and Classes11. Objects and Classes
11. Objects and ClassesIntro C# Book
 
Vision academy classes_bcs_bca_bba_java part_2
Vision academy classes_bcs_bca_bba_java part_2Vision academy classes_bcs_bca_bba_java part_2
Vision academy classes_bcs_bca_bba_java part_2NayanTapare1
 
FP 201 - Unit4 Part 2
FP 201 - Unit4 Part 2FP 201 - Unit4 Part 2
FP 201 - Unit4 Part 2rohassanie
 
When to use a structure vs classes in c++
When to use a structure vs classes in c++When to use a structure vs classes in c++
When to use a structure vs classes in c++Naman Kumar
 
Java 2 chapter 10 - basic oop in java
Java 2   chapter 10 - basic oop in javaJava 2   chapter 10 - basic oop in java
Java 2 chapter 10 - basic oop in javalet's go to study
 
Customer Linguistic Profiling
Customer Linguistic ProfilingCustomer Linguistic Profiling
Customer Linguistic ProfilingF789GH
 
C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorC++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorJussi Pohjolainen
 
Constructor in c++
Constructor in c++Constructor in c++
Constructor in c++Jay Patel
 
2013 11 CSharp Tutorial Struct and Class
2013 11 CSharp Tutorial Struct and Class2013 11 CSharp Tutorial Struct and Class
2013 11 CSharp Tutorial Struct and ClassHung-Wei Liu
 
What's New in C++ 11/14?
What's New in C++ 11/14?What's New in C++ 11/14?
What's New in C++ 11/14?Dina Goldshtein
 
Approaching (almost) Any Machine Learning Problem (kaggledays dubai)
Approaching (almost) Any Machine Learning Problem (kaggledays dubai)Approaching (almost) Any Machine Learning Problem (kaggledays dubai)
Approaching (almost) Any Machine Learning Problem (kaggledays dubai)Abhishek Thakur
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classesIntro C# Book
 
358 33 powerpoint-slides_7-structures_chapter-7
358 33 powerpoint-slides_7-structures_chapter-7358 33 powerpoint-slides_7-structures_chapter-7
358 33 powerpoint-slides_7-structures_chapter-7sumitbardhan
 
C programming & data structure [arrays & pointers]
C programming & data structure   [arrays & pointers]C programming & data structure   [arrays & pointers]
C programming & data structure [arrays & pointers]MomenMostafa
 
Dynamics allocation
Dynamics allocationDynamics allocation
Dynamics allocationKumar
 

What's hot (20)

Chapter 4 strings
Chapter 4 stringsChapter 4 strings
Chapter 4 strings
 
Learning with classification and clustering, neural networks
Learning with classification and clustering, neural networksLearning with classification and clustering, neural networks
Learning with classification and clustering, neural networks
 
11. Objects and Classes
11. Objects and Classes11. Objects and Classes
11. Objects and Classes
 
Vision academy classes_bcs_bca_bba_java part_2
Vision academy classes_bcs_bca_bba_java part_2Vision academy classes_bcs_bca_bba_java part_2
Vision academy classes_bcs_bca_bba_java part_2
 
L10
L10L10
L10
 
FP 201 - Unit4 Part 2
FP 201 - Unit4 Part 2FP 201 - Unit4 Part 2
FP 201 - Unit4 Part 2
 
When to use a structure vs classes in c++
When to use a structure vs classes in c++When to use a structure vs classes in c++
When to use a structure vs classes in c++
 
Java 2 chapter 10 - basic oop in java
Java 2   chapter 10 - basic oop in javaJava 2   chapter 10 - basic oop in java
Java 2 chapter 10 - basic oop in java
 
Customer Linguistic Profiling
Customer Linguistic ProfilingCustomer Linguistic Profiling
Customer Linguistic Profiling
 
C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorC++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operator
 
Constructor in c++
Constructor in c++Constructor in c++
Constructor in c++
 
2013 11 CSharp Tutorial Struct and Class
2013 11 CSharp Tutorial Struct and Class2013 11 CSharp Tutorial Struct and Class
2013 11 CSharp Tutorial Struct and Class
 
Constructors & destructors
Constructors & destructorsConstructors & destructors
Constructors & destructors
 
What's New in C++ 11/14?
What's New in C++ 11/14?What's New in C++ 11/14?
What's New in C++ 11/14?
 
Approaching (almost) Any Machine Learning Problem (kaggledays dubai)
Approaching (almost) Any Machine Learning Problem (kaggledays dubai)Approaching (almost) Any Machine Learning Problem (kaggledays dubai)
Approaching (almost) Any Machine Learning Problem (kaggledays dubai)
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
 
358 33 powerpoint-slides_7-structures_chapter-7
358 33 powerpoint-slides_7-structures_chapter-7358 33 powerpoint-slides_7-structures_chapter-7
358 33 powerpoint-slides_7-structures_chapter-7
 
C programming & data structure [arrays & pointers]
C programming & data structure   [arrays & pointers]C programming & data structure   [arrays & pointers]
C programming & data structure [arrays & pointers]
 
Memory Management In C++
Memory Management In C++Memory Management In C++
Memory Management In C++
 
Dynamics allocation
Dynamics allocationDynamics allocation
Dynamics allocation
 

Viewers also liked

Pf cs102 programming-9 [pointers]
Pf cs102 programming-9 [pointers]Pf cs102 programming-9 [pointers]
Pf cs102 programming-9 [pointers]Abdullah khawar
 
Pf cs102 programming-8 [file handling] (1)
Pf cs102 programming-8 [file handling] (1)Pf cs102 programming-8 [file handling] (1)
Pf cs102 programming-8 [file handling] (1)Abdullah khawar
 
Informatie fiche Periodieke Verzendingen
Informatie fiche Periodieke VerzendingenInformatie fiche Periodieke Verzendingen
Informatie fiche Periodieke VerzendingenSteve Jacobs
 
OPORD Tactical foot march mission
OPORD Tactical foot march missionOPORD Tactical foot march mission
OPORD Tactical foot march missionjoel dillabough
 
1.3 La arquitectura a finales del siglo xix
1.3 La arquitectura a finales del siglo xix1.3 La arquitectura a finales del siglo xix
1.3 La arquitectura a finales del siglo xixAntonio Luengo Gil
 
Johan castellanos presentacion power point
Johan castellanos presentacion power pointJohan castellanos presentacion power point
Johan castellanos presentacion power pointjohancastelblanco
 
Nutrición infantil saludable
Nutrición infantil saludableNutrición infantil saludable
Nutrición infantil saludableCenproexFormacion
 
Inducción 150516224412-lva1-app6892
Inducción  150516224412-lva1-app6892Inducción  150516224412-lva1-app6892
Inducción 150516224412-lva1-app6892miletmeledez
 
Bahasa indonesia 1
Bahasa indonesia 1Bahasa indonesia 1
Bahasa indonesia 1SMK
 
Bizerba - Les Français et la consommation de fruits frais - par OpinionWay - ...
Bizerba - Les Français et la consommation de fruits frais - par OpinionWay - ...Bizerba - Les Français et la consommation de fruits frais - par OpinionWay - ...
Bizerba - Les Français et la consommation de fruits frais - par OpinionWay - ...OpinionWay
 
Marco jurídico - Protección de Infraestructuras Críticas
Marco jurídico - Protección de Infraestructuras CríticasMarco jurídico - Protección de Infraestructuras Críticas
Marco jurídico - Protección de Infraestructuras CríticasPribatua
 
Finals BollyT IIMA Chaos 2015 Quiz
Finals BollyT IIMA Chaos 2015 QuizFinals BollyT IIMA Chaos 2015 Quiz
Finals BollyT IIMA Chaos 2015 QuizTauseef Warsi
 
The Very Simple Fantasy Quiz 2016
The Very Simple Fantasy Quiz 2016The Very Simple Fantasy Quiz 2016
The Very Simple Fantasy Quiz 2016Tauseef Warsi
 
Introduction to Information Security
Introduction to Information SecurityIntroduction to Information Security
Introduction to Information SecurityGareth Davies
 
Information security
Information securityInformation security
Information securityLJ PROJECTS
 
Young Pioneer Catalogue
Young Pioneer CatalogueYoung Pioneer Catalogue
Young Pioneer CatalogueYoung Pioneer
 

Viewers also liked (20)

Pf cs102 programming-9 [pointers]
Pf cs102 programming-9 [pointers]Pf cs102 programming-9 [pointers]
Pf cs102 programming-9 [pointers]
 
Pf cs102 programming-8 [file handling] (1)
Pf cs102 programming-8 [file handling] (1)Pf cs102 programming-8 [file handling] (1)
Pf cs102 programming-8 [file handling] (1)
 
Informatie fiche Periodieke Verzendingen
Informatie fiche Periodieke VerzendingenInformatie fiche Periodieke Verzendingen
Informatie fiche Periodieke Verzendingen
 
OPORD Tactical foot march mission
OPORD Tactical foot march missionOPORD Tactical foot march mission
OPORD Tactical foot march mission
 
1.3 La arquitectura a finales del siglo xix
1.3 La arquitectura a finales del siglo xix1.3 La arquitectura a finales del siglo xix
1.3 La arquitectura a finales del siglo xix
 
Johan castellanos presentacion power point
Johan castellanos presentacion power pointJohan castellanos presentacion power point
Johan castellanos presentacion power point
 
SRC-Funeral Coolers
SRC-Funeral CoolersSRC-Funeral Coolers
SRC-Funeral Coolers
 
Nutrición infantil saludable
Nutrición infantil saludableNutrición infantil saludable
Nutrición infantil saludable
 
Beverage Coolers
Beverage CoolersBeverage Coolers
Beverage Coolers
 
Inducción 150516224412-lva1-app6892
Inducción  150516224412-lva1-app6892Inducción  150516224412-lva1-app6892
Inducción 150516224412-lva1-app6892
 
Bahasa indonesia 1
Bahasa indonesia 1Bahasa indonesia 1
Bahasa indonesia 1
 
Bizerba - Les Français et la consommation de fruits frais - par OpinionWay - ...
Bizerba - Les Français et la consommation de fruits frais - par OpinionWay - ...Bizerba - Les Français et la consommation de fruits frais - par OpinionWay - ...
Bizerba - Les Français et la consommation de fruits frais - par OpinionWay - ...
 
Marco jurídico - Protección de Infraestructuras Críticas
Marco jurídico - Protección de Infraestructuras CríticasMarco jurídico - Protección de Infraestructuras Críticas
Marco jurídico - Protección de Infraestructuras Críticas
 
Finals BollyT IIMA Chaos 2015 Quiz
Finals BollyT IIMA Chaos 2015 QuizFinals BollyT IIMA Chaos 2015 Quiz
Finals BollyT IIMA Chaos 2015 Quiz
 
The Very Simple Fantasy Quiz 2016
The Very Simple Fantasy Quiz 2016The Very Simple Fantasy Quiz 2016
The Very Simple Fantasy Quiz 2016
 
Introduction to Information Security
Introduction to Information SecurityIntroduction to Information Security
Introduction to Information Security
 
Information security
Information securityInformation security
Information security
 
Principales Estructuras2
Principales Estructuras2Principales Estructuras2
Principales Estructuras2
 
Clic2010
Clic2010Clic2010
Clic2010
 
Young Pioneer Catalogue
Young Pioneer CatalogueYoung Pioneer Catalogue
Young Pioneer Catalogue
 

Similar to Pf cs102 programming-10 [structs]

CHAPTER -4-class and structure.pptx
CHAPTER -4-class and structure.pptxCHAPTER -4-class and structure.pptx
CHAPTER -4-class and structure.pptxGebruGetachew2
 
Data Structure & Algorithm - Self Referential
Data Structure & Algorithm - Self ReferentialData Structure & Algorithm - Self Referential
Data Structure & Algorithm - Self Referentialbabuk110
 
data structure and c programing concepts
data structure and c programing conceptsdata structure and c programing concepts
data structure and c programing conceptskavitham66441
 
Structure in programming in c or c++ or c# or java
Structure in programming  in c or c++ or c# or javaStructure in programming  in c or c++ or c# or java
Structure in programming in c or c++ or c# or javaSamsil Arefin
 
Structures
StructuresStructures
Structuresselvapon
 
Fundamentals of Structure in C Programming
Fundamentals of Structure in C ProgrammingFundamentals of Structure in C Programming
Fundamentals of Structure in C ProgrammingChandrakantDivate1
 
Structures in C.pptx
Structures in C.pptxStructures in C.pptx
Structures in C.pptxBoni Yeamin
 
slideset 7 structure and union (1).pdf
slideset 7 structure and union (1).pdfslideset 7 structure and union (1).pdf
slideset 7 structure and union (1).pdfHimanshuKansal22
 
VIT351 Software Development VI Unit4
VIT351 Software Development VI Unit4VIT351 Software Development VI Unit4
VIT351 Software Development VI Unit4YOGESH SINGH
 

Similar to Pf cs102 programming-10 [structs] (20)

CHAPTER -4-class and structure.pptx
CHAPTER -4-class and structure.pptxCHAPTER -4-class and structure.pptx
CHAPTER -4-class and structure.pptx
 
Data Structure & Algorithm - Self Referential
Data Structure & Algorithm - Self ReferentialData Structure & Algorithm - Self Referential
Data Structure & Algorithm - Self Referential
 
data structure and c programing concepts
data structure and c programing conceptsdata structure and c programing concepts
data structure and c programing concepts
 
Unit 5 (1)
Unit 5 (1)Unit 5 (1)
Unit 5 (1)
 
Struct
StructStruct
Struct
 
Structure in c
Structure in cStructure in c
Structure in c
 
Structure in programming in c or c++ or c# or java
Structure in programming  in c or c++ or c# or javaStructure in programming  in c or c++ or c# or java
Structure in programming in c or c++ or c# or java
 
Structures
StructuresStructures
Structures
 
Structure
StructureStructure
Structure
 
Fundamentals of Structure in C Programming
Fundamentals of Structure in C ProgrammingFundamentals of Structure in C Programming
Fundamentals of Structure in C Programming
 
1. structure
1. structure1. structure
1. structure
 
Structure in C
Structure in CStructure in C
Structure in C
 
structure1.pdf
structure1.pdfstructure1.pdf
structure1.pdf
 
Structures in C.pptx
Structures in C.pptxStructures in C.pptx
Structures in C.pptx
 
12Structures.pptx
12Structures.pptx12Structures.pptx
12Structures.pptx
 
Unit4 C
Unit4 C Unit4 C
Unit4 C
 
Structures_Final_KLE (2).pptx
Structures_Final_KLE (2).pptxStructures_Final_KLE (2).pptx
Structures_Final_KLE (2).pptx
 
637225564198396290.pdf
637225564198396290.pdf637225564198396290.pdf
637225564198396290.pdf
 
slideset 7 structure and union (1).pdf
slideset 7 structure and union (1).pdfslideset 7 structure and union (1).pdf
slideset 7 structure and union (1).pdf
 
VIT351 Software Development VI Unit4
VIT351 Software Development VI Unit4VIT351 Software Development VI Unit4
VIT351 Software Development VI Unit4
 

Recently uploaded

Digital Transformation Playbook by Graham Ware
Digital Transformation Playbook by Graham WareDigital Transformation Playbook by Graham Ware
Digital Transformation Playbook by Graham WareGraham Ware
 
Top profile Call Girls In Indore [ 7014168258 ] Call Me For Genuine Models We...
Top profile Call Girls In Indore [ 7014168258 ] Call Me For Genuine Models We...Top profile Call Girls In Indore [ 7014168258 ] Call Me For Genuine Models We...
Top profile Call Girls In Indore [ 7014168258 ] Call Me For Genuine Models We...gajnagarg
 
💞 Safe And Secure Call Girls Agra Call Girls Service Just Call 🍑👄6378878445 🍑...
💞 Safe And Secure Call Girls Agra Call Girls Service Just Call 🍑👄6378878445 🍑...💞 Safe And Secure Call Girls Agra Call Girls Service Just Call 🍑👄6378878445 🍑...
💞 Safe And Secure Call Girls Agra Call Girls Service Just Call 🍑👄6378878445 🍑...vershagrag
 
Top profile Call Girls In dimapur [ 7014168258 ] Call Me For Genuine Models W...
Top profile Call Girls In dimapur [ 7014168258 ] Call Me For Genuine Models W...Top profile Call Girls In dimapur [ 7014168258 ] Call Me For Genuine Models W...
Top profile Call Girls In dimapur [ 7014168258 ] Call Me For Genuine Models W...gajnagarg
 
Top profile Call Girls In Rohtak [ 7014168258 ] Call Me For Genuine Models We...
Top profile Call Girls In Rohtak [ 7014168258 ] Call Me For Genuine Models We...Top profile Call Girls In Rohtak [ 7014168258 ] Call Me For Genuine Models We...
Top profile Call Girls In Rohtak [ 7014168258 ] Call Me For Genuine Models We...nirzagarg
 
Jual obat aborsi Bandung ( 085657271886 ) Cytote pil telat bulan penggugur ka...
Jual obat aborsi Bandung ( 085657271886 ) Cytote pil telat bulan penggugur ka...Jual obat aborsi Bandung ( 085657271886 ) Cytote pil telat bulan penggugur ka...
Jual obat aborsi Bandung ( 085657271886 ) Cytote pil telat bulan penggugur ka...Klinik kandungan
 
怎样办理圣地亚哥州立大学毕业证(SDSU毕业证书)成绩单学校原版复制
怎样办理圣地亚哥州立大学毕业证(SDSU毕业证书)成绩单学校原版复制怎样办理圣地亚哥州立大学毕业证(SDSU毕业证书)成绩单学校原版复制
怎样办理圣地亚哥州立大学毕业证(SDSU毕业证书)成绩单学校原版复制vexqp
 
Top profile Call Girls In Satna [ 7014168258 ] Call Me For Genuine Models We ...
Top profile Call Girls In Satna [ 7014168258 ] Call Me For Genuine Models We ...Top profile Call Girls In Satna [ 7014168258 ] Call Me For Genuine Models We ...
Top profile Call Girls In Satna [ 7014168258 ] Call Me For Genuine Models We ...nirzagarg
 
Identify Customer Segments to Create Customer Offers for Each Segment - Appli...
Identify Customer Segments to Create Customer Offers for Each Segment - Appli...Identify Customer Segments to Create Customer Offers for Each Segment - Appli...
Identify Customer Segments to Create Customer Offers for Each Segment - Appli...ThinkInnovation
 
Predicting HDB Resale Prices - Conducting Linear Regression Analysis With Orange
Predicting HDB Resale Prices - Conducting Linear Regression Analysis With OrangePredicting HDB Resale Prices - Conducting Linear Regression Analysis With Orange
Predicting HDB Resale Prices - Conducting Linear Regression Analysis With OrangeThinkInnovation
 
Nirala Nagar / Cheap Call Girls In Lucknow Phone No 9548273370 Elite Escort S...
Nirala Nagar / Cheap Call Girls In Lucknow Phone No 9548273370 Elite Escort S...Nirala Nagar / Cheap Call Girls In Lucknow Phone No 9548273370 Elite Escort S...
Nirala Nagar / Cheap Call Girls In Lucknow Phone No 9548273370 Elite Escort S...HyderabadDolls
 
Aspirational Block Program Block Syaldey District - Almora
Aspirational Block Program Block Syaldey District - AlmoraAspirational Block Program Block Syaldey District - Almora
Aspirational Block Program Block Syaldey District - AlmoraGovindSinghDasila
 
Top profile Call Girls In Nandurbar [ 7014168258 ] Call Me For Genuine Models...
Top profile Call Girls In Nandurbar [ 7014168258 ] Call Me For Genuine Models...Top profile Call Girls In Nandurbar [ 7014168258 ] Call Me For Genuine Models...
Top profile Call Girls In Nandurbar [ 7014168258 ] Call Me For Genuine Models...gajnagarg
 
In Riyadh ((+919101817206)) Cytotec kit @ Abortion Pills Saudi Arabia
In Riyadh ((+919101817206)) Cytotec kit @ Abortion Pills Saudi ArabiaIn Riyadh ((+919101817206)) Cytotec kit @ Abortion Pills Saudi Arabia
In Riyadh ((+919101817206)) Cytotec kit @ Abortion Pills Saudi Arabiaahmedjiabur940
 
Case Study 4 Where the cry of rebellion happen?
Case Study 4 Where the cry of rebellion happen?Case Study 4 Where the cry of rebellion happen?
Case Study 4 Where the cry of rebellion happen?RemarkSemacio
 
RESEARCH-FINAL-DEFENSE-PPT-TEMPLATE.pptx
RESEARCH-FINAL-DEFENSE-PPT-TEMPLATE.pptxRESEARCH-FINAL-DEFENSE-PPT-TEMPLATE.pptx
RESEARCH-FINAL-DEFENSE-PPT-TEMPLATE.pptxronsairoathenadugay
 
Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
Top profile Call Girls In bhavnagar [ 7014168258 ] Call Me For Genuine Models...
Top profile Call Girls In bhavnagar [ 7014168258 ] Call Me For Genuine Models...Top profile Call Girls In bhavnagar [ 7014168258 ] Call Me For Genuine Models...
Top profile Call Girls In bhavnagar [ 7014168258 ] Call Me For Genuine Models...gajnagarg
 
DATA SUMMIT 24 Building Real-Time Pipelines With FLaNK
DATA SUMMIT 24  Building Real-Time Pipelines With FLaNKDATA SUMMIT 24  Building Real-Time Pipelines With FLaNK
DATA SUMMIT 24 Building Real-Time Pipelines With FLaNKTimothy Spann
 
Sealdah % High Class Call Girls Kolkata - 450+ Call Girl Cash Payment 8005736...
Sealdah % High Class Call Girls Kolkata - 450+ Call Girl Cash Payment 8005736...Sealdah % High Class Call Girls Kolkata - 450+ Call Girl Cash Payment 8005736...
Sealdah % High Class Call Girls Kolkata - 450+ Call Girl Cash Payment 8005736...HyderabadDolls
 

Recently uploaded (20)

Digital Transformation Playbook by Graham Ware
Digital Transformation Playbook by Graham WareDigital Transformation Playbook by Graham Ware
Digital Transformation Playbook by Graham Ware
 
Top profile Call Girls In Indore [ 7014168258 ] Call Me For Genuine Models We...
Top profile Call Girls In Indore [ 7014168258 ] Call Me For Genuine Models We...Top profile Call Girls In Indore [ 7014168258 ] Call Me For Genuine Models We...
Top profile Call Girls In Indore [ 7014168258 ] Call Me For Genuine Models We...
 
💞 Safe And Secure Call Girls Agra Call Girls Service Just Call 🍑👄6378878445 🍑...
💞 Safe And Secure Call Girls Agra Call Girls Service Just Call 🍑👄6378878445 🍑...💞 Safe And Secure Call Girls Agra Call Girls Service Just Call 🍑👄6378878445 🍑...
💞 Safe And Secure Call Girls Agra Call Girls Service Just Call 🍑👄6378878445 🍑...
 
Top profile Call Girls In dimapur [ 7014168258 ] Call Me For Genuine Models W...
Top profile Call Girls In dimapur [ 7014168258 ] Call Me For Genuine Models W...Top profile Call Girls In dimapur [ 7014168258 ] Call Me For Genuine Models W...
Top profile Call Girls In dimapur [ 7014168258 ] Call Me For Genuine Models W...
 
Top profile Call Girls In Rohtak [ 7014168258 ] Call Me For Genuine Models We...
Top profile Call Girls In Rohtak [ 7014168258 ] Call Me For Genuine Models We...Top profile Call Girls In Rohtak [ 7014168258 ] Call Me For Genuine Models We...
Top profile Call Girls In Rohtak [ 7014168258 ] Call Me For Genuine Models We...
 
Jual obat aborsi Bandung ( 085657271886 ) Cytote pil telat bulan penggugur ka...
Jual obat aborsi Bandung ( 085657271886 ) Cytote pil telat bulan penggugur ka...Jual obat aborsi Bandung ( 085657271886 ) Cytote pil telat bulan penggugur ka...
Jual obat aborsi Bandung ( 085657271886 ) Cytote pil telat bulan penggugur ka...
 
怎样办理圣地亚哥州立大学毕业证(SDSU毕业证书)成绩单学校原版复制
怎样办理圣地亚哥州立大学毕业证(SDSU毕业证书)成绩单学校原版复制怎样办理圣地亚哥州立大学毕业证(SDSU毕业证书)成绩单学校原版复制
怎样办理圣地亚哥州立大学毕业证(SDSU毕业证书)成绩单学校原版复制
 
Top profile Call Girls In Satna [ 7014168258 ] Call Me For Genuine Models We ...
Top profile Call Girls In Satna [ 7014168258 ] Call Me For Genuine Models We ...Top profile Call Girls In Satna [ 7014168258 ] Call Me For Genuine Models We ...
Top profile Call Girls In Satna [ 7014168258 ] Call Me For Genuine Models We ...
 
Identify Customer Segments to Create Customer Offers for Each Segment - Appli...
Identify Customer Segments to Create Customer Offers for Each Segment - Appli...Identify Customer Segments to Create Customer Offers for Each Segment - Appli...
Identify Customer Segments to Create Customer Offers for Each Segment - Appli...
 
Predicting HDB Resale Prices - Conducting Linear Regression Analysis With Orange
Predicting HDB Resale Prices - Conducting Linear Regression Analysis With OrangePredicting HDB Resale Prices - Conducting Linear Regression Analysis With Orange
Predicting HDB Resale Prices - Conducting Linear Regression Analysis With Orange
 
Nirala Nagar / Cheap Call Girls In Lucknow Phone No 9548273370 Elite Escort S...
Nirala Nagar / Cheap Call Girls In Lucknow Phone No 9548273370 Elite Escort S...Nirala Nagar / Cheap Call Girls In Lucknow Phone No 9548273370 Elite Escort S...
Nirala Nagar / Cheap Call Girls In Lucknow Phone No 9548273370 Elite Escort S...
 
Aspirational Block Program Block Syaldey District - Almora
Aspirational Block Program Block Syaldey District - AlmoraAspirational Block Program Block Syaldey District - Almora
Aspirational Block Program Block Syaldey District - Almora
 
Top profile Call Girls In Nandurbar [ 7014168258 ] Call Me For Genuine Models...
Top profile Call Girls In Nandurbar [ 7014168258 ] Call Me For Genuine Models...Top profile Call Girls In Nandurbar [ 7014168258 ] Call Me For Genuine Models...
Top profile Call Girls In Nandurbar [ 7014168258 ] Call Me For Genuine Models...
 
In Riyadh ((+919101817206)) Cytotec kit @ Abortion Pills Saudi Arabia
In Riyadh ((+919101817206)) Cytotec kit @ Abortion Pills Saudi ArabiaIn Riyadh ((+919101817206)) Cytotec kit @ Abortion Pills Saudi Arabia
In Riyadh ((+919101817206)) Cytotec kit @ Abortion Pills Saudi Arabia
 
Case Study 4 Where the cry of rebellion happen?
Case Study 4 Where the cry of rebellion happen?Case Study 4 Where the cry of rebellion happen?
Case Study 4 Where the cry of rebellion happen?
 
RESEARCH-FINAL-DEFENSE-PPT-TEMPLATE.pptx
RESEARCH-FINAL-DEFENSE-PPT-TEMPLATE.pptxRESEARCH-FINAL-DEFENSE-PPT-TEMPLATE.pptx
RESEARCH-FINAL-DEFENSE-PPT-TEMPLATE.pptx
 
Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Top profile Call Girls In bhavnagar [ 7014168258 ] Call Me For Genuine Models...
Top profile Call Girls In bhavnagar [ 7014168258 ] Call Me For Genuine Models...Top profile Call Girls In bhavnagar [ 7014168258 ] Call Me For Genuine Models...
Top profile Call Girls In bhavnagar [ 7014168258 ] Call Me For Genuine Models...
 
DATA SUMMIT 24 Building Real-Time Pipelines With FLaNK
DATA SUMMIT 24  Building Real-Time Pipelines With FLaNKDATA SUMMIT 24  Building Real-Time Pipelines With FLaNK
DATA SUMMIT 24 Building Real-Time Pipelines With FLaNK
 
Sealdah % High Class Call Girls Kolkata - 450+ Call Girl Cash Payment 8005736...
Sealdah % High Class Call Girls Kolkata - 450+ Call Girl Cash Payment 8005736...Sealdah % High Class Call Girls Kolkata - 450+ Call Girl Cash Payment 8005736...
Sealdah % High Class Call Girls Kolkata - 450+ Call Girl Cash Payment 8005736...
 

Pf cs102 programming-10 [structs]

  • 2. 2 Structures • A Structure is a collection of related data items, possibly of different types. • A structure type in C++ is called struct. • A struct is heterogeneous in that it can be composed of data of different types. • In contrast, array is homogeneous since it can contain only data of the same type.
  • 3. 3 Structures • Structures hold data that belong together. • Examples: – Student record: student id, name, major, gender, start year, … – Bank account: account number, name, currency, balance, … – Address book: name, address, telephone number, … • In database applications, structures are called records.
  • 4. 4 Structures • Individual components of a struct type are called members (or fields). • Members can be of different types (simple, array or struct). • A struct is named as a whole while individual members are named using field identifiers. • Complex data structures can be formed by defining arrays of structs.
  • 5. 5 struct basics • Definition of a structure: struct <struct-type>{ <type> <identifier_list>; <type> <identifier_list>; ... } ; • Example: struct Date { int day; int month; int year; } ; The “Date” structure has 3 members, day, month & year. Each identifier defines a member of the structure.
  • 6. 6 struct examples • Example: struct StudentInfo{ int Id; int age; char Gender; double CGA; }; • Example: struct StudentGrade{ char Name[15]; char Course[9]; int Lab[5]; int Homework[3]; int Exam[2]; }; The “StudentGrade” structure has 5 members of different array types. The “StudentInfo” structure has 4 members of different types.
  • 7. 7 struct examples • Example: struct BankAccount{ char Name[15]; int AcountNo[10]; double balance; Date Birthday; }; • Example: struct StudentRecord{ char Name[15]; int Id; char Dept[5]; char Gender; }; The “StudentRecord” structure has 4 members. The “BankAcount” structure has simple, array and structure types as members.
  • 8. 8 struct basics • Declaration of a variable of struct type: <struct-type> <identifier_list>; • Example: StudentRecord Student1, Student2; Student1 and Student2 are variables of StudentRecord type. Student1 Student2 Name Id Gender Dept Name Id Gender Dept
  • 9. 9 Chan Tai Man 12345 M COMP Ex. 1: struct basics • The members of a struct type variable are accessed with the dot (.) operator: <struct-variable>.<member_name>; • Example: strcpy(Student1.Name, "Chan Tai Man"); Student1.Id = 12345; strcpy(Student1.Dept, "COMP"); Student1.gender = 'M'; cout << "The student is "; switch (Student1.gender){ case 'F': cout << "Ms. "; break; case 'M': cout << "Mr. "; break; } cout << Student1.Name << endl; Student1 Name Id Gender Dept
  • 10. Records (structs) • struct: collection of a fixed number of components (members), accessed by name – Members may be of different types • Syntax: 10
  • 11. Records (structs) (cont'd.) • A struct is a definition, not a declaration 11
  • 13. Accessing struct Members • The syntax for accessing a struct member is: • The dot (.) is an operator, called the member access operator 13
  • 14. Accessing struct Members (cont'd.) • To initialize the members of newStudent: newStudent.GPA = 0.0; newStudent.firstName = "John"; newStudent.lastName = "Brown"; 14
  • 15. Accessing struct Members (cont'd.) • More examples: cin >> newStudent.firstName; cin >> newStudent.testScore >> newStudent.programmingScore; score = (newStudent.testScore + newStudent.programmingScore) / 2; 15
  • 16. Accessing struct Members (cont'd.) if (score >= 90) newStudent.courseGrade = 'A'; else if (score >= 80) newStudent.courseGrade = 'B'; else if (score >= 70) newStudent.courseGrade = 'C'; else if (score >= 60) newStudent.courseGrade = 'D'; else newStudent.courseGrade = 'F'; 16
  • 17. Example Movie Struct // example about structures #include <iostream> #include <string> using namespace std; struct movies_t { string title; int year; } mine, yours; void printmovie (movies_t movie); int main () { string mystr; mine.title = "2001 A Space Odyssey"; mine.year = 1968; cout << "Enter title: "; getline (cin,yours.title); cout << "Enter year: "; getline (cin,mystr); cin>> yours.year; cout << "My favorite movie is:n "; printmovie (mine); cout << "And yours is:n "; printmovie (yours); return 0; } void printmovie (movies_t movie) { cout << movie.title; cout << " (" << movie.year << ")n"; } 17
  • 18. Example Conti… Enter title: Alien Enter year: 1979 My favorite movie is: 2001 A Space Odyssey (1968) And yours is: Alien (1979) 18
  • 19. Assignment • Value of one struct variable can be assigned to another struct variable of the same type using an assignment statement • The statement: student = newStudent; copies the contents of newStudent into student 19
  • 20. Assignment (cont'd.) • The assignment statement: student = newStudent; is equivalent to the following statements: student.firstName = newStudent.firstName; student.lastName = newStudent.lastName; student.courseGrade = newStudent.courseGrade; student.testScore = newStudent.testScore; student.programmingScore = newStudent.programmingScore; student.GPA = newStudent.GPA; 20
  • 21. Comparison (Relational Operators) • Compare struct variables member- wise – No aggregate relational operations allowed • To compare the values of student and newStudent: 21
  • 22. Input/Output • No aggregate input/output operations on a struct variable • Data in a struct variable must be read one member at a time • The contents of a struct variable must be written one member at a time 22
  • 23. struct Variables and Functions • A struct variable can be passed as a parameter by value or by reference • A function can return a value of type struct 23
  • 25. Arrays in structs • Two key items are associated with a list: – Values (elements) – Length of the list • Define a struct containing both items: 25
  • 26. Arrays in structs (cont'd.) 26
  • 27. 27 Arrays in structs (cont'd.)
  • 29. 29 structs in Arrays (cont’d.)
  • 30. 30 structs in Arrays (cont’d.)
  • 31. structs within a struct 31 versus
  • 32. Structs, and Pointer Variables • You can declare pointers to other data types: – student is an object of type studentType; studentPtr is a pointer variable of type studentType 32
  • 33. Structs, and Pointer Variables (cont'd.) • To store address of student in studentPtr: studentPtr = &student; • To store 3.9 in component gpa of student: (*studentPtr).gpa = 3.9; – () used because dot operator has higher precedence than dereferencing operator – Alternative: use member access operator arrow (->) 33
  • 34. Movie Example // pointers to structures #include <iostream> #include <string> using namespace std; struct movies_t { string title; int year; }; int main () { string mystr; movies_t amovie; movies_t * pmovie; pmovie = &amovie; cout << "Enter title: "; getline (cin, pmovie->title); cout << "Enter year: "; getline (cin, mystr); (stringstream) mystr >> pmovie->year; cout << "nYou have entered:n"; cout << pmovie->title; cout << " (" << pmovie- >year << ")n"; return 0; } 34
  • 35. Example Output… Enter title: Invasion of the body snatchers Enter year: 1978 You have entered: Invasion of the body snatchers (1978) 35
  • 36. Example … pmovie->title is equivalent to (*pmovie).title *pmovie.title is equivalent to *(pmovie.title) 36
  • 37. Pointers & Structs Expression What is evaluated Equivalent a.b Member b of object a a->b Member b of object pointed by a (*a).b *a.b Value pointed by member b of object a *(a.b) 37
  • 38. Structs & File Handling • A file may be read record by record. 38
  • 40. Point Struct with functions struct Point{ int x; int y; void init(){ x=0; y=0; } void init(int a, int b) // Overloaded Function { x=a; y=b; } void input(){ cout<<"nEnter value of X: "; cin>>x; cout<<"nEnter value of Y:"; cin>>y; } void print(){ cout<< "(" << x << "," << y <<")"; } }; 40 void main() { Point p1,p2,p3={10,6},p4; // All seem fine p1.init(); p1.print(); p2.init(2,3); p2.print(); p3.print(); p4.input(); p4.print(); } //Output… (0,0) (2,3) (10,6) Enter value of X: 44 Enter value of Y:55 (44,55)
  • 41. STUDENT’S HOME WORK Sales Data Analysis 41
  • 42. Programming Example: Sales Data Analysis • A company has six salespeople • Every month they go on road trips to sell the company’s product • At the end of each month, the total sales for each salesperson, salesperson’s ID, and the month, are recorded in a file • At the end of each year, the manager of the company asks for a report 42
  • 43. Programming Example: Output Format ----------- Annual Sales Report ------------- ID QT1 QT2 QT3 QT4 Total ______________________________________________________________ 12345 1892.00 0.00 494.00 322.00 2708.00 32214 343.00 892.00 9023.00 0.00 10258.00 23422 1395.00 1901.00 0.00 0.00 3296.00 57373 893.00 892.00 8834.00 0.00 10619.00 35864 2882.00 1221.00 0.00 1223.00 5326.00 54654 893.00 0.00 392.00 3420.00 4705.00 Total 8298.00 4906.00 18743.00 4965.00 Max Sale by SalesPerson: ID = 57373, Amount = $10619.00 Max Sale by Quarter: Quarter = 3, Amount = $18743.00 QT1 stands for quarter 1 (months 1 to 3), QT2 for quarter 2 (months 4 to 6), QT3 for quarter 3 (months 7 to 9), and QT4 for quarter 4 (months 10 to 12) 43
  • 44. Programming Example: Output Format (cont'd.) • The salespeople IDs are stored in one file; sales data are stored in another file • The sales data is in the following form: salesPersonID month saleAmount . . . • Sales data are not ordered 44
  • 45. Programming Example: Input/Output • Input: file containing each salesperson’s ID and a second file containing the sales data • Output: file containing annual sales report in the above format 45
  • 46. Programming Example: Problem Analysis • Main components for each salesperson: – ID – Quarterly sales amount – Total annual sales amount • Use a struct to group the components • Six people: array of size six • Program requires total sales for each quarter – Use array of size four to store the data 46
  • 47. Programming Example: Problem Analysis (cont'd.) 47
  • 48. Programming Example: Problem Analysis (cont'd.) • Read the salespeople IDs into the array salesPersonList • Initialize the quarterly sales and total sales for each salesperson to 0 48
  • 49. Programming Example: Problem Analysis (cont'd.) • For each entry in the file with the sales data: – Read ID, month, sale amount for the month – Search salesPersonList to locate the component corresponding to this salesperson – Determine the quarter corresponding to the month – Update the sales for the quarter by adding the sale amount for the month 49
  • 50. Programming Example: Problem Analysis (cont'd.) • Once the sales data file is processed: – Calculate the total sale by salesperson – Calculate the total sale by quarter – Print the report 50
  • 51. Programming Example: Algorithm Design • Translates into the following algorithm: – Initialize the array salesPersonList – Process the sales data – Calculate the total sale by salesperson – Calculate the total sale by quarter – Print the report – Calculate and print maximum sale by salesperson – Calculate and print maximum sale by quarter 51
  • 52. Programming Example: Main Algorithm • Declare the variables • Prompt user to enter name of file containing the salesperson’s ID data • Read the name of the input file • Open the input file • If input file does not exist, exit • Initialize the array salesPersonList by calling the function initialize 52
  • 53. Programming Example: Main Algorithm (cont'd.) • Close input file containing salesperson’s ID • Prompt user to enter name of file containing sales data • Read the name of the input file • Open the input file • If input file does not exist, exit • Prompt user to enter name of output file • Read the name of the output file 53
  • 54. Programming Example: Main Algorithm (cont'd.) • Open the output file • Output data to two decimal places • Process sales data – Call the function getData • Calculate the total sale by quarter by calling the function saleByQuarter • Calculate the total sale by salesperson by calling the function totalSaleByPerson 54
  • 55. Programming Example: Main Algorithm (cont'd.) • Print the report in the tabular form; call the function printReport • Find and print the salesperson who produces the maximum sales for the year by calling maxSaleByPerson • Find and print the quarter producing the maximum sale for the year by calling maxSaleByQuarter • Close files 55
  • 56. Summary • struct: collection of a fixed number of components • Components can be of different types – Called members – Accessed by name • struct is a reserved word • No memory is allocated for a struct – Memory when variables are declared 56
  • 57. Summary (cont'd.) • Dot (.) operator: member access operator – Used to access members of a struct • The only built-in operations on a struct are the assignment and member access • Neither arithmetic nor relational operations are allowed on structs • struct can be passed by value or reference • A function can return a value of type struct • structs can be members of other structs 57

Editor's Notes

  1. Remind chapter – II Three types of data types (simple, structures, pointers) Variables to store data of int float…. What is the purpose of a avariable …? Where these varibels are stored . . . RAM ? How to see the address of a vaaibrl inside the memory …
  2. http://www.learncpp.com/cpp-tutorial/47-structs/