SlideShare a Scribd company logo
Structures
(CS1123)
By
Dr. Muhammad Aleem,
Department of Computer Science,
Mohammad Ali Jinnah University, Islamabad
Fall Semester 2013
Introducing Structures
 A structure is a collection of multiple data types
that can be referenced with single name.
 The data items in structure are called structure
members, elements, or fields.
 The difference between array and structure: is that
array must consists of a set of values of same data
type but on the other hand, structure may consists
of different data types.
Defining the Structure
• Structure definition tells how
the structure is organized: it
specifies what members the
structure will contain.
Syntax & Example 
Syntax:
struct StructName
{
DataType1 Identifier1;
DataType2 Identifier2;
.
.
.
};
Example:
struct Product
{
int ID;
string name;
float price;
};
Structure Definition Syntax
Declaring a Structure variable
• Structure variable can be defined after the definition of
a structure. The syntax of the declaration is:
StructName Identifier;
Example:
part processor;
part keyboard;
• This declaration tells the compiler to allocate memory
space according to the elements of the structure.
• The structure variable processor and keyboard occupies 12
bytes in the memory. 4 bytes for modelnumber, 4 bytes for
partnumber, 4 bytes for cost
Structure members in memory
struct part
{
int modelnumber;
int partnumber;
float cost;
};
modelnumber
partnumber
cost
4 Bytes
4 Bytes
4 Bytes
Another way of Declaring a Structure variable
• You can also declare struct variables when you
define the struct. For example:
struct part
{
int modelnumber;
int partnumber;
float cost;
} part1;
 These statements define the struct named part and
also declare part1 to be a variable of type part.
Examples
struct employee
{
string firstName;
string lastName;
string address;
double salary;
int deptID;
};
employee e1;
struct student
{
string firstName;
string lastName;
char courseGrade;
int Score;
double CGPA;
} s1, s2;
Initializing Structure Variables
• The syntax of initializing structure is:
StructName struct_identifier = {Value1, Value2, …};
Structure Variable Initialization with Declaration
Note: Values should be written in the same sequence in which
they are specified in structure definition.
struct student
{
string firstName;
string lastName;
char courseGrade;
int marks;
};
void main( )
{
student BC022010= {“M”, “Umar”, ‘A’, 94} ;
}
Assigning Values to Structure Variables
• After creating structure variable, values to structure
members can be assigned using dot (.) operator
• The syntax is as follows:
student BC111017;
BC111017.firstName = “Muhammad”;
BC111017.lastName = “Umar”;
BC111017.courseGrade = ‘A’;
BC111017.marks = 93;
Assigning Values to Structure Variables
• After creating structure variable, values to structure
members can be assigned using cin.
• Output to screen using cout
student BC012311;
cin>>BC012311.firstName;
cin>>BC012311.lastName;
cin>>BC012311.courseGrade;
cin>>BC012311.marks ;
cout<<BC012311.firstName<<BC012311.lastName;
Assigning one Structure Variable to another
• A structure variable can be assigned to another
structure variable only if both are of same type
• A structure variable can be initialized by assigning
another structure variable to it by using the assignment
operator as follows:
Example:
studentType newStudent = {“John”, “Lee”, ‘A’, 99} ;
studentType student2 = newStudent;
Array of Structures
• An array can also be created of user-defined type such as:
structure.
• An array of structure is a type of array in which each element
contains a complete structure.
struct Book
{
int ID;
int Pages;
float Price;
};
Book MAJULibrary[100]; // declaration of array of structures
MAJULibrary[0]
ID Pages Price
…MAJULibrary[1]
ID Pages Price
MAJULibrary[99]
ID Pages Price
Initialization of Array of Structures
struct Book
{
int ID;
int Pages;
float Price;
};
Book b[3]; // declaration of array of structures
• Initializing can be at the time of declaration
Book b[3] = {{1,275,70},{2,600,90},{3,786,100}};
• Or can be assigned values using cin:
cin>>b[0].ID ;
cin>>b[0].Pages;
cin>>b[0].Price;
Array as Member of Structures
• A structure may also contain arrays as members.
struct Student
{
int RollNo;
float Marks[3];
};
• Initialization can be done at time of declaration:
Student S = {1, {70.0, 90.0, 97.0} };
Array as Member of Structures
• Or it can be assigned values later in the program:
Student S;
S.RollNo = 1;
S.Marks[0] = 70.0;
S.Marks[1] = 90.0;
S.Marks[2] = 97.0;
• Or user can use cin to get input directly:
cin>>S.RollNo;
cin>>S.Marks[0];
cin>>S.Marks[1];
cin>>S.Marks[2];
Nested Structure
• A structure can be a member of another structure:
called nesting of structure
struct A
{
int x;
double y;
};
struct B
{
char ch;
A v1;
};
B record;
record
v1
xch y
Initializing/Assigning to Nested Structure
struct A{
int x;
float y;
};
struct B{
char ch;
A v2;
};
void main()
{
B record;
cin>>record.ch;
cin>>record.v2.x;
cin>>record.v2.y;
}
void main()
{
B record = {‘S’, {100, 3.6} };
}
void main()
{
B record;
record.ch = ‘S’;
record.v2.x = 100;
record.v2.y = 3.6;
}
Lecture: 06/01/2014
Accessing Structures with Pointers
• Pointer variables can be used to point to structure
type variables too.
• The pointer variable should be of same type, for
example: structure type
struct Rectangle {
int width;
int height;
};
void main( )
{
Rectangle rect1={22,33};
Rectangle* rect1Ptr = &rect1;
}
Accessing Structures with Pointers
• How to access the structure members (using
pointer)?
– Use dereferencing operator (*) with dot (.) operator
struct Rectangle {
int width;
int height;
};
void main( )
{
Rectangle rect1={22,33};
Rectangle* rectPtr = &rect1;
cout<< (*rectPrt).width<<(*rectPrt).height;
}
Accessing Structures with Pointers
• Is there some easier way also?
– Use arrow operator ( -> )
struct Rectangle {
int width;
int height;
};
void main( )
{
Rectangle rect1={22,33};
Rectangle* rectPtr = &rect1;
cout<< rectPrt->width<<rectPrt->height;
}
Class Exercises(1) – Find Errors
• Find errors:
struct
{
int x;
float y;
};
struct values
{
char name[20];
int age;
}
Class Exercises(2) – Find Errors
• Find errors:
struct TwoVals
{
int a,b;
};
void main()
{
TwoVals.a=10;
TwoVals.b=20;
}
Class Exercises(3) – Find Errors
• Find errors:
struct ThreeVals
{
int a,b,c;
};
int main()
{
ThreeVals vals={1,2,3};
cout<<vals<<endl;
return 0;
}
Class Exercises(4) – Find Errors
• Find errors:
struct names
{
char first[20];
char last[20];
};
int main()
{
names customer = {“Muhammad”, “Ali”};
cout<<names.first<<endl;
cout<<names.last<<endl;
return 0;
}
Class Exercises(5) – Find Errors
• Find errors:
struct TwoVals
{
int a=5;
int b=10;
};
int main()
{
TwoVals v;
cout<<v.a<<“ “<<v.b;
return 0;
}
Class Exercise-6
• Define a structure called “car”. The member elements
of the car structure are:
• string Model;
• int Year;
• float Price
Create an array of 30 cars. Get input for all 30 cars
from the user. Then the program should display
complete information (Model, Year, Price) of those
cars only which are above 500000 in price.
Class Exercise-7
• Write a program that implements the following using C++
struct. The program should finally displays the values
stored in a phone directory (for 10 people)
PhoneNoName
City Country
Address
PhoneDirectory

More Related Content

PPTX
Constructors
PPTX
Constructor and Destructor in c++
PPT
structure
PDF
Structures
PPTX
Structure & Union in C++
PPT
Structure in c
PPTX
Constructor ppt
PPTX
Structure in c language
Constructors
Constructor and Destructor in c++
structure
Structures
Structure & Union in C++
Structure in c
Constructor ppt
Structure in c language

What's hot (20)

DOCX
Structure in c sharp
PPTX
Structure & union
PDF
Structures in c++
PDF
Lecture18 structurein c.ppt
PPT
Structures
PPTX
constructors in java ppt
PPTX
Constructor&method
PPTX
Constructor and Types of Constructors
PPTX
Pf cs102 programming-10 [structs]
PDF
2013 11 CSharp Tutorial Struct and Class
PPT
Structure c
PPT
Constructor & Destructor
PPTX
Structure in C
PPTX
Arrays, Structures And Enums
PPTX
When to use a structure vs classes in c++
PPT
Structure in C
PPTX
C++Constructors
PPTX
Constructor and destructor in oop
PDF
Constructor and Destructor
Structure in c sharp
Structure & union
Structures in c++
Lecture18 structurein c.ppt
Structures
constructors in java ppt
Constructor&method
Constructor and Types of Constructors
Pf cs102 programming-10 [structs]
2013 11 CSharp Tutorial Struct and Class
Structure c
Constructor & Destructor
Structure in C
Arrays, Structures And Enums
When to use a structure vs classes in c++
Structure in C
C++Constructors
Constructor and destructor in oop
Constructor and Destructor
Ad

Viewers also liked (14)

PPT
Eee3420 lecture06 rev2011
PPT
Savitch Ch 15
PPT
Savitch ch 01
PPTX
Structures bmn
PPT
FP 201 - Unit 3 Part 2
PPTX
INTRODUCTION TO C++, Chapter 1
PPT
Fp201 unit4
PPT
Ch7 structures
PPT
Software Engineering-R.D.Sivakumar
PPT
Basic structure of C++ program
PPT
Structure of C++ - R.D.Sivakumar
PPTX
c++ programming Unit 2 basic structure of a c++ program
PPTX
Basic c++ programs
PPT
FP 201 - Unit4 Part 2
Eee3420 lecture06 rev2011
Savitch Ch 15
Savitch ch 01
Structures bmn
FP 201 - Unit 3 Part 2
INTRODUCTION TO C++, Chapter 1
Fp201 unit4
Ch7 structures
Software Engineering-R.D.Sivakumar
Basic structure of C++ program
Structure of C++ - R.D.Sivakumar
c++ programming Unit 2 basic structure of a c++ program
Basic c++ programs
FP 201 - Unit4 Part 2
Ad

Similar to Cs1123 12 structures (20)

PPTX
12Structures.pptx
PPTX
ECE2102-Week13 - 14-Strhhhhhhhjjjucts.pptx
PPTX
Coding - L30-L31-Array of structures.pptx
PPTX
Lab 13
PDF
Data Structure & Algorithm - Self Referential
PPTX
CHAPTER -4-class and structure.pptx
PPTX
Unit-V.pptx
PPT
Structures
PPTX
User defined data types.pptx
DOCX
PPS 8.8.BASIC ALGORITHMS SEARCHING (LINEAR SEARCH, BINARY SEARCH ETC.)
PPTX
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
PPT
358 33 powerpoint-slides_7-structures_chapter-7
PPTX
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
PPTX
Chapter 2 part II array and structure.pptx
PPTX
Computer Programming -II (Lec. 10).pptx
PPTX
Structures
PPTX
C programing -Structure
PPTX
Structure and Union .pptx program in C with detailed example
PPTX
Structures_Final_KLE (2).pptx
PDF
1. structure
12Structures.pptx
ECE2102-Week13 - 14-Strhhhhhhhjjjucts.pptx
Coding - L30-L31-Array of structures.pptx
Lab 13
Data Structure & Algorithm - Self Referential
CHAPTER -4-class and structure.pptx
Unit-V.pptx
Structures
User defined data types.pptx
PPS 8.8.BASIC ALGORITHMS SEARCHING (LINEAR SEARCH, BINARY SEARCH ETC.)
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
358 33 powerpoint-slides_7-structures_chapter-7
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
Chapter 2 part II array and structure.pptx
Computer Programming -II (Lec. 10).pptx
Structures
C programing -Structure
Structure and Union .pptx program in C with detailed example
Structures_Final_KLE (2).pptx
1. structure

More from TAlha MAlik (12)

PPTX
Data file handling
PPTX
Cs1123 11 pointers
PPTX
Cs1123 10 file operations
PPTX
Cs1123 8 functions
PPTX
Cs1123 6 loops
PPTX
Cs1123 7 arrays
PPTX
Cs1123 5 selection_if
PPTX
Cs1123 4 variables_constants
PPTX
Cs1123 3 c++ overview
PPTX
Cs1123 2 comp_prog
PPTX
Cs1123 1 intro
PPTX
Cs1123 9 strings
Data file handling
Cs1123 11 pointers
Cs1123 10 file operations
Cs1123 8 functions
Cs1123 6 loops
Cs1123 7 arrays
Cs1123 5 selection_if
Cs1123 4 variables_constants
Cs1123 3 c++ overview
Cs1123 2 comp_prog
Cs1123 1 intro
Cs1123 9 strings

Recently uploaded (20)

PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
cuic standard and advanced reporting.pdf
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Empathic Computing: Creating Shared Understanding
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPTX
A Presentation on Artificial Intelligence
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
NewMind AI Monthly Chronicles - July 2025
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PPT
Teaching material agriculture food technology
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Modernizing your data center with Dell and AMD
PDF
Review of recent advances in non-invasive hemoglobin estimation
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Per capita expenditure prediction using model stacking based on satellite ima...
cuic standard and advanced reporting.pdf
Mobile App Security Testing_ A Comprehensive Guide.pdf
Digital-Transformation-Roadmap-for-Companies.pptx
Empathic Computing: Creating Shared Understanding
Reach Out and Touch Someone: Haptics and Empathic Computing
A Presentation on Artificial Intelligence
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
NewMind AI Monthly Chronicles - July 2025
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Teaching material agriculture food technology
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
NewMind AI Weekly Chronicles - August'25 Week I
Encapsulation_ Review paper, used for researhc scholars
Understanding_Digital_Forensics_Presentation.pptx
MYSQL Presentation for SQL database connectivity
Modernizing your data center with Dell and AMD
Review of recent advances in non-invasive hemoglobin estimation

Cs1123 12 structures

  • 1. Structures (CS1123) By Dr. Muhammad Aleem, Department of Computer Science, Mohammad Ali Jinnah University, Islamabad Fall Semester 2013
  • 2. Introducing Structures  A structure is a collection of multiple data types that can be referenced with single name.  The data items in structure are called structure members, elements, or fields.  The difference between array and structure: is that array must consists of a set of values of same data type but on the other hand, structure may consists of different data types.
  • 3. Defining the Structure • Structure definition tells how the structure is organized: it specifies what members the structure will contain. Syntax & Example  Syntax: struct StructName { DataType1 Identifier1; DataType2 Identifier2; . . . }; Example: struct Product { int ID; string name; float price; };
  • 5. Declaring a Structure variable • Structure variable can be defined after the definition of a structure. The syntax of the declaration is: StructName Identifier; Example: part processor; part keyboard; • This declaration tells the compiler to allocate memory space according to the elements of the structure. • The structure variable processor and keyboard occupies 12 bytes in the memory. 4 bytes for modelnumber, 4 bytes for partnumber, 4 bytes for cost
  • 6. Structure members in memory struct part { int modelnumber; int partnumber; float cost; }; modelnumber partnumber cost 4 Bytes 4 Bytes 4 Bytes
  • 7. Another way of Declaring a Structure variable • You can also declare struct variables when you define the struct. For example: struct part { int modelnumber; int partnumber; float cost; } part1;  These statements define the struct named part and also declare part1 to be a variable of type part.
  • 8. Examples struct employee { string firstName; string lastName; string address; double salary; int deptID; }; employee e1; struct student { string firstName; string lastName; char courseGrade; int Score; double CGPA; } s1, s2;
  • 9. Initializing Structure Variables • The syntax of initializing structure is: StructName struct_identifier = {Value1, Value2, …};
  • 10. Structure Variable Initialization with Declaration Note: Values should be written in the same sequence in which they are specified in structure definition. struct student { string firstName; string lastName; char courseGrade; int marks; }; void main( ) { student BC022010= {“M”, “Umar”, ‘A’, 94} ; }
  • 11. Assigning Values to Structure Variables • After creating structure variable, values to structure members can be assigned using dot (.) operator • The syntax is as follows: student BC111017; BC111017.firstName = “Muhammad”; BC111017.lastName = “Umar”; BC111017.courseGrade = ‘A’; BC111017.marks = 93;
  • 12. Assigning Values to Structure Variables • After creating structure variable, values to structure members can be assigned using cin. • Output to screen using cout student BC012311; cin>>BC012311.firstName; cin>>BC012311.lastName; cin>>BC012311.courseGrade; cin>>BC012311.marks ; cout<<BC012311.firstName<<BC012311.lastName;
  • 13. Assigning one Structure Variable to another • A structure variable can be assigned to another structure variable only if both are of same type • A structure variable can be initialized by assigning another structure variable to it by using the assignment operator as follows: Example: studentType newStudent = {“John”, “Lee”, ‘A’, 99} ; studentType student2 = newStudent;
  • 14. Array of Structures • An array can also be created of user-defined type such as: structure. • An array of structure is a type of array in which each element contains a complete structure. struct Book { int ID; int Pages; float Price; }; Book MAJULibrary[100]; // declaration of array of structures MAJULibrary[0] ID Pages Price …MAJULibrary[1] ID Pages Price MAJULibrary[99] ID Pages Price
  • 15. Initialization of Array of Structures struct Book { int ID; int Pages; float Price; }; Book b[3]; // declaration of array of structures • Initializing can be at the time of declaration Book b[3] = {{1,275,70},{2,600,90},{3,786,100}}; • Or can be assigned values using cin: cin>>b[0].ID ; cin>>b[0].Pages; cin>>b[0].Price;
  • 16. Array as Member of Structures • A structure may also contain arrays as members. struct Student { int RollNo; float Marks[3]; }; • Initialization can be done at time of declaration: Student S = {1, {70.0, 90.0, 97.0} };
  • 17. Array as Member of Structures • Or it can be assigned values later in the program: Student S; S.RollNo = 1; S.Marks[0] = 70.0; S.Marks[1] = 90.0; S.Marks[2] = 97.0; • Or user can use cin to get input directly: cin>>S.RollNo; cin>>S.Marks[0]; cin>>S.Marks[1]; cin>>S.Marks[2];
  • 18. Nested Structure • A structure can be a member of another structure: called nesting of structure struct A { int x; double y; }; struct B { char ch; A v1; }; B record; record v1 xch y
  • 19. Initializing/Assigning to Nested Structure struct A{ int x; float y; }; struct B{ char ch; A v2; }; void main() { B record; cin>>record.ch; cin>>record.v2.x; cin>>record.v2.y; } void main() { B record = {‘S’, {100, 3.6} }; } void main() { B record; record.ch = ‘S’; record.v2.x = 100; record.v2.y = 3.6; }
  • 21. Accessing Structures with Pointers • Pointer variables can be used to point to structure type variables too. • The pointer variable should be of same type, for example: structure type struct Rectangle { int width; int height; }; void main( ) { Rectangle rect1={22,33}; Rectangle* rect1Ptr = &rect1; }
  • 22. Accessing Structures with Pointers • How to access the structure members (using pointer)? – Use dereferencing operator (*) with dot (.) operator struct Rectangle { int width; int height; }; void main( ) { Rectangle rect1={22,33}; Rectangle* rectPtr = &rect1; cout<< (*rectPrt).width<<(*rectPrt).height; }
  • 23. Accessing Structures with Pointers • Is there some easier way also? – Use arrow operator ( -> ) struct Rectangle { int width; int height; }; void main( ) { Rectangle rect1={22,33}; Rectangle* rectPtr = &rect1; cout<< rectPrt->width<<rectPrt->height; }
  • 24. Class Exercises(1) – Find Errors • Find errors: struct { int x; float y; }; struct values { char name[20]; int age; }
  • 25. Class Exercises(2) – Find Errors • Find errors: struct TwoVals { int a,b; }; void main() { TwoVals.a=10; TwoVals.b=20; }
  • 26. Class Exercises(3) – Find Errors • Find errors: struct ThreeVals { int a,b,c; }; int main() { ThreeVals vals={1,2,3}; cout<<vals<<endl; return 0; }
  • 27. Class Exercises(4) – Find Errors • Find errors: struct names { char first[20]; char last[20]; }; int main() { names customer = {“Muhammad”, “Ali”}; cout<<names.first<<endl; cout<<names.last<<endl; return 0; }
  • 28. Class Exercises(5) – Find Errors • Find errors: struct TwoVals { int a=5; int b=10; }; int main() { TwoVals v; cout<<v.a<<“ “<<v.b; return 0; }
  • 29. Class Exercise-6 • Define a structure called “car”. The member elements of the car structure are: • string Model; • int Year; • float Price Create an array of 30 cars. Get input for all 30 cars from the user. Then the program should display complete information (Model, Year, Price) of those cars only which are above 500000 in price.
  • 30. Class Exercise-7 • Write a program that implements the following using C++ struct. The program should finally displays the values stored in a phone directory (for 10 people) PhoneNoName City Country Address PhoneDirectory