SlideShare a Scribd company logo
1 of 25
Structures
Lecture No 3
COMSATS Institute of
Information & Technology
2

Structures







Ordinary variables can hold one piece of
information.
Arrays can hold a number of pieces of
information of the same data type.
Quite often we deal with entities that are
collection of dissimilar data types.
Want to store data about a book.
Want to store its name (a string), its price (a
float) and number of pages in it (an int).
Object Oriented Programming
3

Structures
C

and C++ support data structures that
can store combinations of character,
integer floating point and enumerated
type data. They are called structs.
 In general, we can say a structure is a
collection of different types of data.

Object Oriented Programming
4

„C++‟ implementation of
Structure
The keyword „struct‟ is used for creating a
structure.
 Syntax:
struct structure-name
{
datatype1 varname1;
datatype1 varname2;
datatype1 varname3;
};
creating the object of structure:
Struct structure-name var1, var2, var3;


Object Oriented Programming
5

Declaration
struct list {
int roll;
char name[10];
float marks;
};
struct list a , b , c;
It is equivalent to:
struct list {
int roll;
char name[10];
float marks;
}a, b, c;

Object Oriented Programming
6

Reserves Space
Declaring Structures (struct)

Does Not Reserve Space
struct my_example
{
int label;
char letter;
char name[20];

struct my_example
{
int label;
char letter;
char name[20];
} mystruct ;

};

/* The name "my_example" is
called a structure tag

*/

Object Oriented Programming
7

Accessing Struct Members


Individual members of a struct variable may be
accessed using the structure member operator (the
dot, “.” member access operator)
mystruct.letter ;



Or , if a pointer to the struct has been declared and
initialized
Some_name *myptr = &mystruct ;
by using the structure pointer operator (the “->“):
myptr -> letter ;
which could also be written as:
(*myptr).letter ;
Object Oriented Programming
8

Accessing structure elements


. (dot operator) is used to access individual structure element
e.g.
struct list
{
int roll;
char name[10];
float marks;
};
struct list a , b , c;
a.roll––is the integer element of structure a.
a.name––is char array element of structure a.
b.marks––is a float element of structure b.
a.marks––is a float element of structure b.
scanf( “%d”, &b.roll); this statement can accept an integer roll of structure
from user. This is applied to all the elements of a structure.

Object Oriented Programming
9

Things to remember:


The closing brace in the structure type declaration must be
followed by a semicolon.



Structure type declaration does not tell the compiler to
reserve any space in memory. All a structure declaration
does is, it defines the „form‟ of the structure.



Usually structure type declaration appears at the top of the
source code file, before any variables or functions are
defined. In very large programs they are usually put in a
separate header file, and the file is included (using the
preprocessor directive #include) in whichever program we
want to use this structure type.

Object Oriented Programming
10

How Structure Elements are
Stored :

 Whatever

be the elements of a structure, they are
always stored in contiguous memory locations.
/*Memory map of structure elements*/
main()
{ struct book
{ char name;
float price;
int pages;
};
struct book b1 = {„B‟, 130.00, 550};
Object Oriented Programming
11

Output:

Object Oriented Programming
12

Array of Structures:
 To

store data of 100 books we would be
required to use 100 different structure
variables from b1 to b100,

A

better approach would be to use an
array of structures.

Object Oriented Programming
13

/* Usage of an array of structures */
main( )
{
struct book
{
char name ;
float price ;
int pages ;
};
struct book b[100] ;
int i ;
Object Oriented Programming
14

for ( i = 0 ; i <= 99 ; i++ )
{
cout << "nEnter name, price and pages " ;
cin >> b[i].name, b[i].price, b[i].pages;
}
for ( i = 0 ; i <= 99 ; i++ )
cout << b[i].name, b[i].price, b[i].pages <<endl;
}

Object Oriented Programming
15

Passing structure to a function:
Struct Test
{
int marks;
Char grade;
};
void show(Test p);
void main()
{
Test t;
cout <<“Enter marks:”
cin>>t.marks;
cout <<“Enter grade:”
cin>>t.grade;
show(t);
getch();
}

Object Oriented Programming
16

void show(Test p)
{
cout<<“Marks:”<<p.marks<<endl;
cout<<“Grade:”<<p.grade<<endl;
}

Object Oriented Programming
17

Structure Pointers:
 The

way we can have a pointer pointing
to an int, or a pointer pointing to a char,
similarly we can have a pointer pointing
to a struct.

Object Oriented Programming
18

struct Book
{
char author[30];
Int pages;
Int price
}
Void main()
{
Book rec, *ptr;
ptr = &rec;
cout<<“Enter author name:”;
cin.get(ptr->author, 30);

Object Oriented Programming
19

cout<<“Enter pages:”;
cin>>ptr->pages;
cout<<“Author:”<<ptr->author<<endl;
cout<<“Pages:”<<ptr->pages<<endl;
}

Object Oriented Programming
20

Structures within Structures
struct date
{

int day, month, year;

};
struct employrec
{
char name[20[;
char id[20];
float salary;
struct date hiredate;
};
struct employrec employees;

To access the field day of structure type date,
employees.hiredate.day = 10;
Object Oriented Programming
21

User Defined Data Types
(typedef)


The C language provides a facility called typedef
for creating synonyms for previously defined data
type names. For example, the declaration:
typedef int Length;



makes the name Length a synonym (or alias) for
the data type int.
The data “type” name Length can now be used in
declarations in exactly the same way that the
data type int can be used:
Length a, b, len ;
Length numbers[10] ;
Object Oriented Programming
22

Typedef & Struct
 Often,

typedef is used in combination with struct to
declare a synonym (or an alias) for a structure:
typedef struct
{
int label ;
char letter;
char name[20] ;
} Some_name ;
Some_name mystruct ;
*/

/* Define a structure */

/* The "alias" is Some_name */
/* Create a struct variable
Object Oriented Programming
23

Enumeration


Enumeration is essentially a method of creating a
numbered list. It allows the user to assign names to
numbers which can then be used as indices in an
array



Enumeration is a user-defined data type. It is defined using
the keyword enum and the syntax is:
enum tag_name {name_0, …, name_n} ;



The tag_name is not used directly. The names in the braces
are symbolic constants that take on integer values from
zero through n. As an example, the statement:
enum colors { red, yellow, green } ;
creates three constants. red is assigned the value 0, yellow
is assigned 1 and green is assigned 2.



Object Oriented Programming
24

Enumeration
/* This program uses enumerated data types to
access the elements of an array */
#include <stdio.h>
int main( )
{
int March[5][7]={{0,0,1,2,3,4,5},{6,7,8,9,10,11,12},
{13,14,15,16,17,18,19},{20,21,22,23,24,25,26},
{27,28,29,30,31,0,0}};
enum days {Sunday, Monday, Tuesday,
Wednesday, Thursday, Friday, Saturday};
Object Oriented Programming
25

Enumeration
enum week {week_one, week_two,
week_three,
week_four, week_five};
printf ("Monday the third week "
"of March is March %dn",
March [week_three] [Monday] );

}
Object Oriented Programming

More Related Content

What's hot

2CPP06 - Arrays and Pointers
2CPP06 - Arrays and Pointers2CPP06 - Arrays and Pointers
2CPP06 - Arrays and PointersMichael Heron
 
Assignment c programming
Assignment c programmingAssignment c programming
Assignment c programmingIcaii Infotech
 
C programming structure & pointer
C  programming structure & pointerC  programming structure & pointer
C programming structure & pointerargusacademy
 
C programming(part 3)
C programming(part 3)C programming(part 3)
C programming(part 3)SURBHI SAROHA
 
detailed information about Pointers in c language
detailed information about Pointers in c languagedetailed information about Pointers in c language
detailed information about Pointers in c languagegourav kottawar
 
Pointer and polymorphism
Pointer and polymorphismPointer and polymorphism
Pointer and polymorphismSangeethaSasi1
 
Array in c language
Array in c language Array in c language
Array in c language umesh patil
 
Module 5-Structure and Union
Module 5-Structure and UnionModule 5-Structure and Union
Module 5-Structure and Unionnikshaikh786
 
Structures in c language
Structures in c languageStructures in c language
Structures in c languagetanmaymodi4
 
Structure and Typedef
Structure and TypedefStructure and Typedef
Structure and TypedefAcad
 
Embedded C The IoT Academy
Embedded C The IoT AcademyEmbedded C The IoT Academy
Embedded C The IoT AcademyThe IOT Academy
 
2.overview of c++ ________lecture2
2.overview of c++  ________lecture22.overview of c++  ________lecture2
2.overview of c++ ________lecture2Warui Maina
 
structure and union
structure and unionstructure and union
structure and unionstudent
 

What's hot (20)

2CPP06 - Arrays and Pointers
2CPP06 - Arrays and Pointers2CPP06 - Arrays and Pointers
2CPP06 - Arrays and Pointers
 
Assignment c programming
Assignment c programmingAssignment c programming
Assignment c programming
 
C programming structure & pointer
C  programming structure & pointerC  programming structure & pointer
C programming structure & pointer
 
Pointers
 Pointers Pointers
Pointers
 
2nd section
2nd section2nd section
2nd section
 
C programming(part 3)
C programming(part 3)C programming(part 3)
C programming(part 3)
 
detailed information about Pointers in c language
detailed information about Pointers in c languagedetailed information about Pointers in c language
detailed information about Pointers in c language
 
C Programming Assignment
C Programming AssignmentC Programming Assignment
C Programming Assignment
 
Pointer and polymorphism
Pointer and polymorphismPointer and polymorphism
Pointer and polymorphism
 
Structure
StructureStructure
Structure
 
Array in c language
Array in c language Array in c language
Array in c language
 
Module 5-Structure and Union
Module 5-Structure and UnionModule 5-Structure and Union
Module 5-Structure and Union
 
Structures in c language
Structures in c languageStructures in c language
Structures in c language
 
Typedef
TypedefTypedef
Typedef
 
Lecture 18 - Pointers
Lecture 18 - PointersLecture 18 - Pointers
Lecture 18 - Pointers
 
Structure and Typedef
Structure and TypedefStructure and Typedef
Structure and Typedef
 
Lecture 6- Intorduction to C Programming
Lecture 6- Intorduction to C ProgrammingLecture 6- Intorduction to C Programming
Lecture 6- Intorduction to C Programming
 
Embedded C The IoT Academy
Embedded C The IoT AcademyEmbedded C The IoT Academy
Embedded C The IoT Academy
 
2.overview of c++ ________lecture2
2.overview of c++  ________lecture22.overview of c++  ________lecture2
2.overview of c++ ________lecture2
 
structure and union
structure and unionstructure and union
structure and union
 

Viewers also liked

Viewers also liked (7)

Ch3
Ch3Ch3
Ch3
 
Lec4
Lec4Lec4
Lec4
 
Ch2
Ch2Ch2
Ch2
 
Ch5
Ch5Ch5
Ch5
 
Ch4
Ch4Ch4
Ch4
 
Ch1
Ch1Ch1
Ch1
 
02 20110314-simulation
02 20110314-simulation02 20110314-simulation
02 20110314-simulation
 

Similar to Oop lec 3(structures) (20)

U5 SPC.pptx
U5 SPC.pptxU5 SPC.pptx
U5 SPC.pptx
 
U5 SPC.pptx
U5 SPC.pptxU5 SPC.pptx
U5 SPC.pptx
 
[ITP - Lecture 16] Structures in C/C++
[ITP - Lecture 16] Structures in C/C++[ITP - Lecture 16] Structures in C/C++
[ITP - Lecture 16] Structures in C/C++
 
03 structures
03 structures03 structures
03 structures
 
Unit-V.pptx
Unit-V.pptxUnit-V.pptx
Unit-V.pptx
 
OOC MODULE1.pptx
OOC MODULE1.pptxOOC MODULE1.pptx
OOC MODULE1.pptx
 
C structure and union
C structure and unionC structure and union
C structure and union
 
Lab 13
Lab 13Lab 13
Lab 13
 
Structures
StructuresStructures
Structures
 
Easy Understanding of Structure Union Typedef Enum in C Language.pdf
Easy Understanding of Structure Union Typedef Enum in C Language.pdfEasy Understanding of Structure Union Typedef Enum in C Language.pdf
Easy Understanding of Structure Union Typedef Enum in C Language.pdf
 
Lk module4 structures
Lk module4 structuresLk module4 structures
Lk module4 structures
 
structure.ppt
structure.pptstructure.ppt
structure.ppt
 
structures.ppt
structures.pptstructures.ppt
structures.ppt
 
Introduction to structures in c lang.ppt
Introduction to structures in c lang.pptIntroduction to structures in c lang.ppt
Introduction to structures in c lang.ppt
 
C Programming Unit-4
C Programming Unit-4C Programming Unit-4
C Programming Unit-4
 
Unit4 Slides
Unit4 SlidesUnit4 Slides
Unit4 Slides
 
Unit 4 qba
Unit 4 qbaUnit 4 qba
Unit 4 qba
 
Notes(1).pptx
Notes(1).pptxNotes(1).pptx
Notes(1).pptx
 
Pointers and Structures
Pointers and StructuresPointers and Structures
Pointers and Structures
 
OOP-Lecture-05 (Constructor_Destructor).pptx
OOP-Lecture-05 (Constructor_Destructor).pptxOOP-Lecture-05 (Constructor_Destructor).pptx
OOP-Lecture-05 (Constructor_Destructor).pptx
 

More from Asfand Hassan

Pak US relation 130411005046-phpapp01
Pak US relation 130411005046-phpapp01Pak US relation 130411005046-phpapp01
Pak US relation 130411005046-phpapp01Asfand Hassan
 
Course outline [csc241 object oriented programming]
Course outline [csc241 object oriented programming]Course outline [csc241 object oriented programming]
Course outline [csc241 object oriented programming]Asfand Hassan
 
Oop lec 2(introduction to object oriented technology)
Oop lec 2(introduction to object oriented technology)Oop lec 2(introduction to object oriented technology)
Oop lec 2(introduction to object oriented technology)Asfand Hassan
 
Oop lec 4(oop design, style, characteristics)
Oop lec 4(oop design, style, characteristics)Oop lec 4(oop design, style, characteristics)
Oop lec 4(oop design, style, characteristics)Asfand Hassan
 
Course outline [csc241 object oriented programming]
Course outline [csc241 object oriented programming]Course outline [csc241 object oriented programming]
Course outline [csc241 object oriented programming]Asfand Hassan
 
Oop lec 5-(class objects, constructor & destructor)
Oop lec 5-(class objects, constructor & destructor)Oop lec 5-(class objects, constructor & destructor)
Oop lec 5-(class objects, constructor & destructor)Asfand Hassan
 

More from Asfand Hassan (13)

Pak US relation 130411005046-phpapp01
Pak US relation 130411005046-phpapp01Pak US relation 130411005046-phpapp01
Pak US relation 130411005046-phpapp01
 
Chap5java5th
Chap5java5thChap5java5th
Chap5java5th
 
Chap6java5th
Chap6java5thChap6java5th
Chap6java5th
 
Chap4java5th
Chap4java5thChap4java5th
Chap4java5th
 
Chap3java5th
Chap3java5thChap3java5th
Chap3java5th
 
Chap2java5th
Chap2java5thChap2java5th
Chap2java5th
 
Chap1java5th
Chap1java5thChap1java5th
Chap1java5th
 
Course outline [csc241 object oriented programming]
Course outline [csc241 object oriented programming]Course outline [csc241 object oriented programming]
Course outline [csc241 object oriented programming]
 
Oop lec 2(introduction to object oriented technology)
Oop lec 2(introduction to object oriented technology)Oop lec 2(introduction to object oriented technology)
Oop lec 2(introduction to object oriented technology)
 
Oop lec 4(oop design, style, characteristics)
Oop lec 4(oop design, style, characteristics)Oop lec 4(oop design, style, characteristics)
Oop lec 4(oop design, style, characteristics)
 
Oop lec 1
Oop lec 1Oop lec 1
Oop lec 1
 
Course outline [csc241 object oriented programming]
Course outline [csc241 object oriented programming]Course outline [csc241 object oriented programming]
Course outline [csc241 object oriented programming]
 
Oop lec 5-(class objects, constructor & destructor)
Oop lec 5-(class objects, constructor & destructor)Oop lec 5-(class objects, constructor & destructor)
Oop lec 5-(class objects, constructor & destructor)
 

Recently uploaded

Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 

Recently uploaded (20)

Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 

Oop lec 3(structures)

  • 1. Structures Lecture No 3 COMSATS Institute of Information & Technology
  • 2. 2 Structures      Ordinary variables can hold one piece of information. Arrays can hold a number of pieces of information of the same data type. Quite often we deal with entities that are collection of dissimilar data types. Want to store data about a book. Want to store its name (a string), its price (a float) and number of pages in it (an int). Object Oriented Programming
  • 3. 3 Structures C and C++ support data structures that can store combinations of character, integer floating point and enumerated type data. They are called structs.  In general, we can say a structure is a collection of different types of data. Object Oriented Programming
  • 4. 4 „C++‟ implementation of Structure The keyword „struct‟ is used for creating a structure.  Syntax: struct structure-name { datatype1 varname1; datatype1 varname2; datatype1 varname3; }; creating the object of structure: Struct structure-name var1, var2, var3;  Object Oriented Programming
  • 5. 5 Declaration struct list { int roll; char name[10]; float marks; }; struct list a , b , c; It is equivalent to: struct list { int roll; char name[10]; float marks; }a, b, c; Object Oriented Programming
  • 6. 6 Reserves Space Declaring Structures (struct) Does Not Reserve Space struct my_example { int label; char letter; char name[20]; struct my_example { int label; char letter; char name[20]; } mystruct ; }; /* The name "my_example" is called a structure tag */ Object Oriented Programming
  • 7. 7 Accessing Struct Members  Individual members of a struct variable may be accessed using the structure member operator (the dot, “.” member access operator) mystruct.letter ;  Or , if a pointer to the struct has been declared and initialized Some_name *myptr = &mystruct ; by using the structure pointer operator (the “->“): myptr -> letter ; which could also be written as: (*myptr).letter ; Object Oriented Programming
  • 8. 8 Accessing structure elements  . (dot operator) is used to access individual structure element e.g. struct list { int roll; char name[10]; float marks; }; struct list a , b , c; a.roll––is the integer element of structure a. a.name––is char array element of structure a. b.marks––is a float element of structure b. a.marks––is a float element of structure b. scanf( “%d”, &b.roll); this statement can accept an integer roll of structure from user. This is applied to all the elements of a structure. Object Oriented Programming
  • 9. 9 Things to remember:  The closing brace in the structure type declaration must be followed by a semicolon.  Structure type declaration does not tell the compiler to reserve any space in memory. All a structure declaration does is, it defines the „form‟ of the structure.  Usually structure type declaration appears at the top of the source code file, before any variables or functions are defined. In very large programs they are usually put in a separate header file, and the file is included (using the preprocessor directive #include) in whichever program we want to use this structure type. Object Oriented Programming
  • 10. 10 How Structure Elements are Stored :  Whatever be the elements of a structure, they are always stored in contiguous memory locations. /*Memory map of structure elements*/ main() { struct book { char name; float price; int pages; }; struct book b1 = {„B‟, 130.00, 550}; Object Oriented Programming
  • 12. 12 Array of Structures:  To store data of 100 books we would be required to use 100 different structure variables from b1 to b100, A better approach would be to use an array of structures. Object Oriented Programming
  • 13. 13 /* Usage of an array of structures */ main( ) { struct book { char name ; float price ; int pages ; }; struct book b[100] ; int i ; Object Oriented Programming
  • 14. 14 for ( i = 0 ; i <= 99 ; i++ ) { cout << "nEnter name, price and pages " ; cin >> b[i].name, b[i].price, b[i].pages; } for ( i = 0 ; i <= 99 ; i++ ) cout << b[i].name, b[i].price, b[i].pages <<endl; } Object Oriented Programming
  • 15. 15 Passing structure to a function: Struct Test { int marks; Char grade; }; void show(Test p); void main() { Test t; cout <<“Enter marks:” cin>>t.marks; cout <<“Enter grade:” cin>>t.grade; show(t); getch(); } Object Oriented Programming
  • 17. 17 Structure Pointers:  The way we can have a pointer pointing to an int, or a pointer pointing to a char, similarly we can have a pointer pointing to a struct. Object Oriented Programming
  • 18. 18 struct Book { char author[30]; Int pages; Int price } Void main() { Book rec, *ptr; ptr = &rec; cout<<“Enter author name:”; cin.get(ptr->author, 30); Object Oriented Programming
  • 20. 20 Structures within Structures struct date { int day, month, year; }; struct employrec { char name[20[; char id[20]; float salary; struct date hiredate; }; struct employrec employees; To access the field day of structure type date, employees.hiredate.day = 10; Object Oriented Programming
  • 21. 21 User Defined Data Types (typedef)  The C language provides a facility called typedef for creating synonyms for previously defined data type names. For example, the declaration: typedef int Length;  makes the name Length a synonym (or alias) for the data type int. The data “type” name Length can now be used in declarations in exactly the same way that the data type int can be used: Length a, b, len ; Length numbers[10] ; Object Oriented Programming
  • 22. 22 Typedef & Struct  Often, typedef is used in combination with struct to declare a synonym (or an alias) for a structure: typedef struct { int label ; char letter; char name[20] ; } Some_name ; Some_name mystruct ; */ /* Define a structure */ /* The "alias" is Some_name */ /* Create a struct variable Object Oriented Programming
  • 23. 23 Enumeration  Enumeration is essentially a method of creating a numbered list. It allows the user to assign names to numbers which can then be used as indices in an array  Enumeration is a user-defined data type. It is defined using the keyword enum and the syntax is: enum tag_name {name_0, …, name_n} ;  The tag_name is not used directly. The names in the braces are symbolic constants that take on integer values from zero through n. As an example, the statement: enum colors { red, yellow, green } ; creates three constants. red is assigned the value 0, yellow is assigned 1 and green is assigned 2.  Object Oriented Programming
  • 24. 24 Enumeration /* This program uses enumerated data types to access the elements of an array */ #include <stdio.h> int main( ) { int March[5][7]={{0,0,1,2,3,4,5},{6,7,8,9,10,11,12}, {13,14,15,16,17,18,19},{20,21,22,23,24,25,26}, {27,28,29,30,31,0,0}}; enum days {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}; Object Oriented Programming
  • 25. 25 Enumeration enum week {week_one, week_two, week_three, week_four, week_five}; printf ("Monday the third week " "of March is March %dn", March [week_three] [Monday] ); } Object Oriented Programming