SlideShare a Scribd company logo
Structures Intro to Programming
MUHAMMAD HAMMAD WASEEM 1
Why Use Structures
We have seen earlier how ordinary variables can hold one piece of information and how arrays can
hold a number of pieces of information of the same data type. These two data types can handle a great
variety of situations. But quite often we deal with entities that are collection of dissimilar data types.
For example, suppose you want to store data about a book. You might want to store its name (a
string), its price (a float) and number of pages in it (an int). If data about say 3 such books is to
be stored, then we can follow two approaches:
a) Construct individual arrays, one for storing names, another for storing prices and still
another for storing number of pages.
b) Use a structure variable.
A structure contains a number of data types grouped together. These data types may or may not
be of the same type. The following example illustrates the use of this data type.
main( )
{
struct book
{
char name ;
float price ;
int pages ;
} ;
struct book b1, b2, b3 ;
printf ( "nEnter names, prices & no. of pages of 3 booksn" ) ;
scanf ( "%c %f %d", &b1.name, &b1.price, &b1.pages ) ;
scanf ( "%c %f %d", &b2.name, &b2.price, &b2.pages ) ;
scanf ( "%c %f %d", &b3.name, &b3.price, &b3.pages ) ;
printf ( "nAnd this is what you entered" ) ;
printf ( "n%c %f %d", b1.name, b1.price, b1.pages ) ;
printf ( "n%c %f %d", b2.name, b2.price, b2.pages ) ;
printf ( "n%c %f %d", b3.name, b3.price, b3.pages ) ;
}
And here is the output...
Enter names, prices and no. of pages of 3 books
A 100.00 354
C 256.50 682
F 233.70 512
Declaring a Structure
In example program above, the following statement declares the structure type:
struct book
{
char name ;
float price ;
int pages ;
} ;
Structures Intro to Programming
MUHAMMAD HAMMAD WASEEM 2
This statement defines a new data type called struct book. Each variable of this data type will
consist of a character variable called name, a float variable called price and an integer variable called
pages. The general form of a structure declaration statement is given below:
struct <structure name>
{
structure element 1 ;
structure element 2 ;
structure element 3 ;
......
......
} ;
Once the new structure data type has been defined one or more variables can be declared to be of
that type. For example the variables b1, b2, b3 can be declared to be of the type struct book, as,
struct book b1, b2, b3 ;
If we so desire, we can combine the declaration of the structure type and the structure variables in
one statement. For example,
struct book
{
char name ;
float price ;
int pages ;
} ;
struct book b1, b2, b3 ;
is same as...
struct book
{
char name ;
float price ;
int pages ;
} b1, b2, b3 ;
or even...
struct
{
char name ;
float price ;
int pages ;
} b1, b2, b3 ;
Like primary variables and arrays, structure variables can also be initialized where they are
declared. The format used is quite similar to that used to initiate arrays.
struct book
{
char name[10] ;
float price ;
int pages ;
} ;
Structures Intro to Programming
MUHAMMAD HAMMAD WASEEM 3
struct book b1 = { "Basic", 130.00, 550 } ;
struct book b2 = { "Physics", 150.80, 800 } ;
Accessing Structure Elements
In arrays we can access individual elements of an array using a subscript. Structures use a different
scheme. They use a dot (.) operator. So to refer to pages of the structure defined in sample program
we have to use,
b1.pages
Similarly, to refer to price we would use,
b1.price
Note that before the dot there must always be a structure variable and after the dot there must
always be a structure element.
How Structure Elements are Stored
Whatever be the elements of a structure, they are always stored in contiguous memory locations.
The following program would illustrate this:
main( )
{
struct book
{
char name ;
float price ;
int pages ;
} ;
struct book b1 = { 'B', 130.00, 550 } ;
printf ( "nAddress of name = %u", &b1.name ) ;
printf ( "nAddress of price = %u", &b1.price ) ;
printf ( "nAddress of pages = %u", &b1.pages ) ;
}
Here is the output of the program...
Address of name = 65518
Address of price = 65519
Address of pages = 65523
Actually the structure elements are stored in memory as shown in the Figure
Structures Intro to Programming
MUHAMMAD HAMMAD WASEEM 4
Array of Structures
In this program, to store data of 100 books we would be required to use 100 different structure
variables from b1 to b100, which is definitely not very convenient. A better approach would be to use
an array of structures. Following program shows how to use an array of structures.
main( )
{
struct book
{
char name ;
float price ;
int pages ;
} ;
struct book b[100] ;
int i ;
for ( i = 0 ; i <= 99 ; i++ )
{
printf ( "nEnter name, price and pages " ) ;
scanf ( "%c %f %d", &b[i].name, &b[i].price, &b[i].pages ) ;
}
for ( i = 0 ; i <= 99 ; i++ )
printf ( "n%c %f %d", b[i].name, b[i].price, b[i].pages );
}
linkfloat( )
{
float a = 0, *b ;
b = &a ; /* cause emulator to be linked */
a = *b ; /* suppress the warning - variable not used */
}
Now a few explanations about the program:
a) Notice how the array of structures is declared...
struct book b[100] ; This provides space in memory for 100 structures of the type
struct book.
b) The syntax we use to reference each element of the array b is similar to the syntax used for
arrays of ints and chars. For example, we refer to zeroth book’s price as b[0].price.
Similarly, we refer first book’s pages as b[1].pages.
c) It should be appreciated what careful thought Dennis Ritchie has put into C language. He
first defined array as a collection of similar elements; then realized that dissimilar data types
that are often found in real life cannot be handled using arrays, therefore created a new
data type called structure. But even using structures programming convenience could not
be achieved, because a lot of variables (b1 to b100 for storing data about hundred books)
needed to be handled. Therefore he allowed us to create an array of structures; an array of
similar data types which themselves are a collection of dissimilar data types.
d) In an array of structures all elements of the array are stored in adjacent memory locations.
Since each element of this array is a structure, and since all structure elements are always
Structures Intro to Programming
MUHAMMAD HAMMAD WASEEM 5
stored in adjacent locations you can very well visualise the arrangement of array of
structures in memory. In our example, b[0]’s name, price and pages in memory would be
immediately followed by b[1]’s name, price and pages, and so on.
e) What is the function linkfloat( ) doing here? If you don’t define it you are bound to get the
error "Floating Point Formats Not Linked" with majority of C Compilers. What causes this
error to occur? When parsing our source file, if the compiler encounters a reference to the
address of a float, it sets a flag to have the linker link in the floating-point emulator. A
floating point emulator is used to manipulate floating point numbers in runtime library
functions like scanf( ) and atof( ). There are some cases in which the reference to the float is
a bit obscure and the compiler does not detect the need for the emulator. The most
common is using scanf( ) to read a float in an array of structures as shown in our program.
How can we force the formats to be linked? That’s where the linkfloat( ) function comes in. It forces
linking of the floating-point emulator into an application. There is no need to call this function, just
define it anywhere in your program.
Uses of Structures
Where are structures useful? The immediate application that comes to the mind is Database
Management. That is, to maintain data about employees in an organization, books in a library, items in
a store, financial accounting transactions in a company etc. But mind you, use of structures stretches
much beyond database management. They can be used for a variety of purposes like:
a) Changing the size of the cursor
b) Clearing the contents of the screen
c) Placing the cursor at an appropriate position on screen
d) Drawing any graphics shape on the screen
e) Receiving a key from the keyboard
f) Checking the memory size of the computer
g) Finding out the list of equipment attached to the computer
h) Formatting a floppy
i) Hiding a file from the directory
j) Displaying the directory of a disk
k) Sending the output to printer
l) Interacting with the mouse
And that is certainly a very impressive list! At least impressive enough to make you realize how
important a data type a structure is and to be thorough with it if you intend to program any of the
above applications.

More Related Content

What's hot

Lecture 18 - Pointers
Lecture 18 - PointersLecture 18 - Pointers
Lecture 18 - Pointers
Md. Imran Hossain Showrov
 
Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4
Saranya saran
 
[ITP - Lecture 12] Functions in C/C++
[ITP - Lecture 12] Functions in C/C++[ITP - Lecture 12] Functions in C/C++
[ITP - Lecture 12] Functions in C/C++
Muhammad Hammad Waseem
 
C Programming Unit-2
C Programming Unit-2C Programming Unit-2
C Programming Unit-2
Vikram Nandini
 
[ITP - Lecture 04] Variables and Constants in C/C++
[ITP - Lecture 04] Variables and Constants in C/C++[ITP - Lecture 04] Variables and Constants in C/C++
[ITP - Lecture 04] Variables and Constants in C/C++
Muhammad Hammad Waseem
 
Arrays
ArraysArrays
Maharishi University of Management (MSc Computer Science test questions)
Maharishi University of Management (MSc Computer Science test questions)Maharishi University of Management (MSc Computer Science test questions)
Maharishi University of Management (MSc Computer Science test questions)
Dharma Kshetri
 
Lecture 8- Data Input and Output
Lecture 8- Data Input and OutputLecture 8- Data Input and Output
Lecture 8- Data Input and Output
Md. Imran Hossain Showrov
 
46630497 fun-pointer-1
46630497 fun-pointer-146630497 fun-pointer-1
46630497 fun-pointer-1
AmIt Prasad
 
C standard library functions
C standard library functionsC standard library functions
C standard library functions
Vaishnavee Sharma
 
[ITP - Lecture 11] Loops in C/C++
[ITP - Lecture 11] Loops in C/C++[ITP - Lecture 11] Loops in C/C++
[ITP - Lecture 11] Loops in C/C++
Muhammad Hammad Waseem
 
Lecture 17 - Strings
Lecture 17 - StringsLecture 17 - Strings
Lecture 17 - Strings
Md. Imran Hossain Showrov
 
Lecture 6- Intorduction to C Programming
Lecture 6- Intorduction to C ProgrammingLecture 6- Intorduction to C Programming
Lecture 6- Intorduction to C Programming
Md. Imran Hossain Showrov
 
Diploma ii cfpc u-4 function, storage class and array and strings
Diploma ii  cfpc u-4 function, storage class and array and stringsDiploma ii  cfpc u-4 function, storage class and array and strings
Diploma ii cfpc u-4 function, storage class and array and strings
Rai University
 
functions in C
functions in Cfunctions in C
functions in C
Mehwish Mehmood
 
C interview question answer 2
C interview question answer 2C interview question answer 2
C interview question answer 2
Amit Kapoor
 
Lecture 9- Control Structures 1
Lecture 9- Control Structures 1Lecture 9- Control Structures 1
Lecture 9- Control Structures 1
Md. Imran Hossain Showrov
 
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdf
MANAGING INPUT AND OUTPUT OPERATIONS IN C    MRS.SOWMYA JYOTHI.pdfMANAGING INPUT AND OUTPUT OPERATIONS IN C    MRS.SOWMYA JYOTHI.pdf
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdf
SowmyaJyothi3
 
Functions torage class and array and strings-
Functions torage class and array and strings-Functions torage class and array and strings-
Functions torage class and array and strings-
aneebkmct
 
Btech i pic u-4 function, storage class and array and strings
Btech i pic u-4 function, storage class and array and stringsBtech i pic u-4 function, storage class and array and strings
Btech i pic u-4 function, storage class and array and strings
Rai University
 

What's hot (20)

Lecture 18 - Pointers
Lecture 18 - PointersLecture 18 - Pointers
Lecture 18 - Pointers
 
Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4
 
[ITP - Lecture 12] Functions in C/C++
[ITP - Lecture 12] Functions in C/C++[ITP - Lecture 12] Functions in C/C++
[ITP - Lecture 12] Functions in C/C++
 
C Programming Unit-2
C Programming Unit-2C Programming Unit-2
C Programming Unit-2
 
[ITP - Lecture 04] Variables and Constants in C/C++
[ITP - Lecture 04] Variables and Constants in C/C++[ITP - Lecture 04] Variables and Constants in C/C++
[ITP - Lecture 04] Variables and Constants in C/C++
 
Arrays
ArraysArrays
Arrays
 
Maharishi University of Management (MSc Computer Science test questions)
Maharishi University of Management (MSc Computer Science test questions)Maharishi University of Management (MSc Computer Science test questions)
Maharishi University of Management (MSc Computer Science test questions)
 
Lecture 8- Data Input and Output
Lecture 8- Data Input and OutputLecture 8- Data Input and Output
Lecture 8- Data Input and Output
 
46630497 fun-pointer-1
46630497 fun-pointer-146630497 fun-pointer-1
46630497 fun-pointer-1
 
C standard library functions
C standard library functionsC standard library functions
C standard library functions
 
[ITP - Lecture 11] Loops in C/C++
[ITP - Lecture 11] Loops in C/C++[ITP - Lecture 11] Loops in C/C++
[ITP - Lecture 11] Loops in C/C++
 
Lecture 17 - Strings
Lecture 17 - StringsLecture 17 - Strings
Lecture 17 - Strings
 
Lecture 6- Intorduction to C Programming
Lecture 6- Intorduction to C ProgrammingLecture 6- Intorduction to C Programming
Lecture 6- Intorduction to C Programming
 
Diploma ii cfpc u-4 function, storage class and array and strings
Diploma ii  cfpc u-4 function, storage class and array and stringsDiploma ii  cfpc u-4 function, storage class and array and strings
Diploma ii cfpc u-4 function, storage class and array and strings
 
functions in C
functions in Cfunctions in C
functions in C
 
C interview question answer 2
C interview question answer 2C interview question answer 2
C interview question answer 2
 
Lecture 9- Control Structures 1
Lecture 9- Control Structures 1Lecture 9- Control Structures 1
Lecture 9- Control Structures 1
 
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdf
MANAGING INPUT AND OUTPUT OPERATIONS IN C    MRS.SOWMYA JYOTHI.pdfMANAGING INPUT AND OUTPUT OPERATIONS IN C    MRS.SOWMYA JYOTHI.pdf
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdf
 
Functions torage class and array and strings-
Functions torage class and array and strings-Functions torage class and array and strings-
Functions torage class and array and strings-
 
Btech i pic u-4 function, storage class and array and strings
Btech i pic u-4 function, storage class and array and stringsBtech i pic u-4 function, storage class and array and strings
Btech i pic u-4 function, storage class and array and strings
 

Similar to [ITP - Lecture 16] Structures in C/C++

03 structures
03 structures03 structures
03 structures
Rajan Gautam
 
Oop lec 3(structures)
Oop lec 3(structures)Oop lec 3(structures)
Oop lec 3(structures)
Asfand Hassan
 
U5 SPC.pptx
U5 SPC.pptxU5 SPC.pptx
U5 SPC.pptx
thenmozhip8
 
U5 SPC.pptx
U5 SPC.pptxU5 SPC.pptx
Data structures
Data structuresData structures
Data structures
Saurabh Mishra
 
Unit-V.pptx
Unit-V.pptxUnit-V.pptx
Unit-V.pptx
Mehul Desai
 
Lecture 3.mte 407
Lecture 3.mte 407Lecture 3.mte 407
Lecture 3.mte 407
rumanatasnim415
 
Programming in C
Programming in CProgramming in C
Programming in C
MalathiNagarajan20
 
C,c++ interview q&a
C,c++ interview q&aC,c++ interview q&a
C,c++ interview q&a
Kumaran K
 
Lk module4 structures
Lk module4 structuresLk module4 structures
Lk module4 structures
Krishna Nanda
 
Unit 4 qba
Unit 4 qbaUnit 4 qba
Unit 4 qba
Sowri Rajan
 
Structures in c++
Structures in c++Structures in c++
Structures in c++
Swarup Boro
 
LEARN C#
LEARN C#LEARN C#
LEARN C#
adroitinfogen
 
Synapseindia dot net development
Synapseindia dot net developmentSynapseindia dot net development
Synapseindia dot net development
Synapseindiappsdevelopment
 
structure.ppt
structure.pptstructure.ppt
structure.ppt
Sheik Mohideen
 
Module 5-Structure and Union
Module 5-Structure and UnionModule 5-Structure and Union
Module 5-Structure and Union
nikshaikh786
 
Structure & union
Structure & unionStructure & union
Structure & union
lalithambiga kamaraj
 
C Structure and Union in C
C Structure and Union in CC Structure and Union in C
ABCs of Programming_eBook Contents
ABCs of Programming_eBook ContentsABCs of Programming_eBook Contents
ABCs of Programming_eBook Contents
Ashley Menhennett
 
Abstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdfAbstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdf
karymadelaneyrenne19
 

Similar to [ITP - Lecture 16] Structures in C/C++ (20)

03 structures
03 structures03 structures
03 structures
 
Oop lec 3(structures)
Oop lec 3(structures)Oop lec 3(structures)
Oop lec 3(structures)
 
U5 SPC.pptx
U5 SPC.pptxU5 SPC.pptx
U5 SPC.pptx
 
U5 SPC.pptx
U5 SPC.pptxU5 SPC.pptx
U5 SPC.pptx
 
Data structures
Data structuresData structures
Data structures
 
Unit-V.pptx
Unit-V.pptxUnit-V.pptx
Unit-V.pptx
 
Lecture 3.mte 407
Lecture 3.mte 407Lecture 3.mte 407
Lecture 3.mte 407
 
Programming in C
Programming in CProgramming in C
Programming in C
 
C,c++ interview q&a
C,c++ interview q&aC,c++ interview q&a
C,c++ interview q&a
 
Lk module4 structures
Lk module4 structuresLk module4 structures
Lk module4 structures
 
Unit 4 qba
Unit 4 qbaUnit 4 qba
Unit 4 qba
 
Structures in c++
Structures in c++Structures in c++
Structures in c++
 
LEARN C#
LEARN C#LEARN C#
LEARN C#
 
Synapseindia dot net development
Synapseindia dot net developmentSynapseindia dot net development
Synapseindia dot net development
 
structure.ppt
structure.pptstructure.ppt
structure.ppt
 
Module 5-Structure and Union
Module 5-Structure and UnionModule 5-Structure and Union
Module 5-Structure and Union
 
Structure & union
Structure & unionStructure & union
Structure & union
 
C Structure and Union in C
C Structure and Union in CC Structure and Union in C
C Structure and Union in C
 
ABCs of Programming_eBook Contents
ABCs of Programming_eBook ContentsABCs of Programming_eBook Contents
ABCs of Programming_eBook Contents
 
Abstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdfAbstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdf
 

More from Muhammad Hammad Waseem

[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++
[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++
[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++
Muhammad Hammad Waseem
 
[ITP - Lecture 09] Conditional Operator in C/C++
[ITP - Lecture 09] Conditional Operator in C/C++[ITP - Lecture 09] Conditional Operator in C/C++
[ITP - Lecture 09] Conditional Operator in C/C++
Muhammad Hammad Waseem
 
[ITP - Lecture 08] Decision Control Structures (If Statement)
[ITP - Lecture 08] Decision Control Structures (If Statement)[ITP - Lecture 08] Decision Control Structures (If Statement)
[ITP - Lecture 08] Decision Control Structures (If Statement)
Muhammad Hammad Waseem
 
[ITP - Lecture 07] Comments in C/C++
[ITP - Lecture 07] Comments in C/C++[ITP - Lecture 07] Comments in C/C++
[ITP - Lecture 07] Comments in C/C++
Muhammad Hammad Waseem
 
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
Muhammad Hammad Waseem
 
[ITP - Lecture 05] Datatypes
[ITP - Lecture 05] Datatypes[ITP - Lecture 05] Datatypes
[ITP - Lecture 05] Datatypes
Muhammad Hammad Waseem
 
[ITP - Lecture 03] Introduction to C/C++
[ITP - Lecture 03] Introduction to C/C++[ITP - Lecture 03] Introduction to C/C++
[ITP - Lecture 03] Introduction to C/C++
Muhammad Hammad Waseem
 
[ITP - Lecture 02] Steps to Create Program & Approaches of Programming
[ITP - Lecture 02] Steps to Create Program & Approaches of Programming[ITP - Lecture 02] Steps to Create Program & Approaches of Programming
[ITP - Lecture 02] Steps to Create Program & Approaches of Programming
Muhammad Hammad Waseem
 
[ITP - Lecture 01] Introduction to Programming & Different Programming Languages
[ITP - Lecture 01] Introduction to Programming & Different Programming Languages[ITP - Lecture 01] Introduction to Programming & Different Programming Languages
[ITP - Lecture 01] Introduction to Programming & Different Programming Languages
Muhammad Hammad Waseem
 
[OOP - Lec 20,21] Inheritance
[OOP - Lec 20,21] Inheritance[OOP - Lec 20,21] Inheritance
[OOP - Lec 20,21] Inheritance
Muhammad Hammad Waseem
 
[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions
Muhammad Hammad Waseem
 
[OOP - Lec 18] Static Data Member
[OOP - Lec 18] Static Data Member[OOP - Lec 18] Static Data Member
[OOP - Lec 18] Static Data Member
Muhammad Hammad Waseem
 
[OOP - Lec 16,17] Objects as Function Parameter and ReturnType
[OOP - Lec 16,17] Objects as Function Parameter and ReturnType[OOP - Lec 16,17] Objects as Function Parameter and ReturnType
[OOP - Lec 16,17] Objects as Function Parameter and ReturnType
Muhammad Hammad Waseem
 
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
Muhammad Hammad Waseem
 
[OOP - Lec 09,10,11] Class Members & their Accessing
[OOP - Lec 09,10,11] Class Members & their Accessing[OOP - Lec 09,10,11] Class Members & their Accessing
[OOP - Lec 09,10,11] Class Members & their Accessing
Muhammad Hammad Waseem
 
[OOP - Lec 08] Encapsulation (Information Hiding)
[OOP - Lec 08] Encapsulation (Information Hiding)[OOP - Lec 08] Encapsulation (Information Hiding)
[OOP - Lec 08] Encapsulation (Information Hiding)
Muhammad Hammad Waseem
 
[OOP - Lec 07] Access Specifiers
[OOP - Lec 07] Access Specifiers[OOP - Lec 07] Access Specifiers
[OOP - Lec 07] Access Specifiers
Muhammad Hammad Waseem
 
[OOP - Lec 06] Classes and Objects
[OOP - Lec 06] Classes and Objects[OOP - Lec 06] Classes and Objects
[OOP - Lec 06] Classes and Objects
Muhammad Hammad Waseem
 
[OOP - Lec 04,05] Basic Building Blocks of OOP
[OOP - Lec 04,05] Basic Building Blocks of OOP[OOP - Lec 04,05] Basic Building Blocks of OOP
[OOP - Lec 04,05] Basic Building Blocks of OOP
Muhammad Hammad Waseem
 
[OOP - Lec 03] Programming Paradigms
[OOP - Lec 03] Programming Paradigms[OOP - Lec 03] Programming Paradigms
[OOP - Lec 03] Programming Paradigms
Muhammad Hammad Waseem
 

More from Muhammad Hammad Waseem (20)

[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++
[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++
[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++
 
[ITP - Lecture 09] Conditional Operator in C/C++
[ITP - Lecture 09] Conditional Operator in C/C++[ITP - Lecture 09] Conditional Operator in C/C++
[ITP - Lecture 09] Conditional Operator in C/C++
 
[ITP - Lecture 08] Decision Control Structures (If Statement)
[ITP - Lecture 08] Decision Control Structures (If Statement)[ITP - Lecture 08] Decision Control Structures (If Statement)
[ITP - Lecture 08] Decision Control Structures (If Statement)
 
[ITP - Lecture 07] Comments in C/C++
[ITP - Lecture 07] Comments in C/C++[ITP - Lecture 07] Comments in C/C++
[ITP - Lecture 07] Comments in C/C++
 
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
 
[ITP - Lecture 05] Datatypes
[ITP - Lecture 05] Datatypes[ITP - Lecture 05] Datatypes
[ITP - Lecture 05] Datatypes
 
[ITP - Lecture 03] Introduction to C/C++
[ITP - Lecture 03] Introduction to C/C++[ITP - Lecture 03] Introduction to C/C++
[ITP - Lecture 03] Introduction to C/C++
 
[ITP - Lecture 02] Steps to Create Program & Approaches of Programming
[ITP - Lecture 02] Steps to Create Program & Approaches of Programming[ITP - Lecture 02] Steps to Create Program & Approaches of Programming
[ITP - Lecture 02] Steps to Create Program & Approaches of Programming
 
[ITP - Lecture 01] Introduction to Programming & Different Programming Languages
[ITP - Lecture 01] Introduction to Programming & Different Programming Languages[ITP - Lecture 01] Introduction to Programming & Different Programming Languages
[ITP - Lecture 01] Introduction to Programming & Different Programming Languages
 
[OOP - Lec 20,21] Inheritance
[OOP - Lec 20,21] Inheritance[OOP - Lec 20,21] Inheritance
[OOP - Lec 20,21] Inheritance
 
[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions
 
[OOP - Lec 18] Static Data Member
[OOP - Lec 18] Static Data Member[OOP - Lec 18] Static Data Member
[OOP - Lec 18] Static Data Member
 
[OOP - Lec 16,17] Objects as Function Parameter and ReturnType
[OOP - Lec 16,17] Objects as Function Parameter and ReturnType[OOP - Lec 16,17] Objects as Function Parameter and ReturnType
[OOP - Lec 16,17] Objects as Function Parameter and ReturnType
 
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
 
[OOP - Lec 09,10,11] Class Members & their Accessing
[OOP - Lec 09,10,11] Class Members & their Accessing[OOP - Lec 09,10,11] Class Members & their Accessing
[OOP - Lec 09,10,11] Class Members & their Accessing
 
[OOP - Lec 08] Encapsulation (Information Hiding)
[OOP - Lec 08] Encapsulation (Information Hiding)[OOP - Lec 08] Encapsulation (Information Hiding)
[OOP - Lec 08] Encapsulation (Information Hiding)
 
[OOP - Lec 07] Access Specifiers
[OOP - Lec 07] Access Specifiers[OOP - Lec 07] Access Specifiers
[OOP - Lec 07] Access Specifiers
 
[OOP - Lec 06] Classes and Objects
[OOP - Lec 06] Classes and Objects[OOP - Lec 06] Classes and Objects
[OOP - Lec 06] Classes and Objects
 
[OOP - Lec 04,05] Basic Building Blocks of OOP
[OOP - Lec 04,05] Basic Building Blocks of OOP[OOP - Lec 04,05] Basic Building Blocks of OOP
[OOP - Lec 04,05] Basic Building Blocks of OOP
 
[OOP - Lec 03] Programming Paradigms
[OOP - Lec 03] Programming Paradigms[OOP - Lec 03] Programming Paradigms
[OOP - Lec 03] Programming Paradigms
 

Recently uploaded

Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"
Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"
Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"
National Information Standards Organization (NISO)
 
MDP on air pollution of class 8 year 2024-2025
MDP on air pollution of class 8 year 2024-2025MDP on air pollution of class 8 year 2024-2025
MDP on air pollution of class 8 year 2024-2025
khuleseema60
 
Gender and Mental Health - Counselling and Family Therapy Applications and In...
Gender and Mental Health - Counselling and Family Therapy Applications and In...Gender and Mental Health - Counselling and Family Therapy Applications and In...
Gender and Mental Health - Counselling and Family Therapy Applications and In...
PsychoTech Services
 
Pharmaceutics Pharmaceuticals best of brub
Pharmaceutics Pharmaceuticals best of brubPharmaceutics Pharmaceuticals best of brub
Pharmaceutics Pharmaceuticals best of brub
danielkiash986
 
spot a liar (Haiqa 146).pptx Technical writhing and presentation skills
spot a liar (Haiqa 146).pptx Technical writhing and presentation skillsspot a liar (Haiqa 146).pptx Technical writhing and presentation skills
spot a liar (Haiqa 146).pptx Technical writhing and presentation skills
haiqairshad
 
Elevate Your Nonprofit's Online Presence_ A Guide to Effective SEO Strategies...
Elevate Your Nonprofit's Online Presence_ A Guide to Effective SEO Strategies...Elevate Your Nonprofit's Online Presence_ A Guide to Effective SEO Strategies...
Elevate Your Nonprofit's Online Presence_ A Guide to Effective SEO Strategies...
TechSoup
 
CHUYÊN ĐỀ ÔN TẬP VÀ PHÁT TRIỂN CÂU HỎI TRONG ĐỀ MINH HỌA THI TỐT NGHIỆP THPT ...
CHUYÊN ĐỀ ÔN TẬP VÀ PHÁT TRIỂN CÂU HỎI TRONG ĐỀ MINH HỌA THI TỐT NGHIỆP THPT ...CHUYÊN ĐỀ ÔN TẬP VÀ PHÁT TRIỂN CÂU HỎI TRONG ĐỀ MINH HỌA THI TỐT NGHIỆP THPT ...
CHUYÊN ĐỀ ÔN TẬP VÀ PHÁT TRIỂN CÂU HỎI TRONG ĐỀ MINH HỌA THI TỐT NGHIỆP THPT ...
Nguyen Thanh Tu Collection
 
Oliver Asks for More by Charles Dickens (9)
Oliver Asks for More by Charles Dickens (9)Oliver Asks for More by Charles Dickens (9)
Oliver Asks for More by Charles Dickens (9)
nitinpv4ai
 
Bonku-Babus-Friend by Sathyajith Ray (9)
Bonku-Babus-Friend by Sathyajith Ray  (9)Bonku-Babus-Friend by Sathyajith Ray  (9)
Bonku-Babus-Friend by Sathyajith Ray (9)
nitinpv4ai
 
A Free 200-Page eBook ~ Brain and Mind Exercise.pptx
A Free 200-Page eBook ~ Brain and Mind Exercise.pptxA Free 200-Page eBook ~ Brain and Mind Exercise.pptx
A Free 200-Page eBook ~ Brain and Mind Exercise.pptx
OH TEIK BIN
 
Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...
Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...
Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...
EduSkills OECD
 
Bossa N’ Roll Records by Ismael Vazquez.
Bossa N’ Roll Records by Ismael Vazquez.Bossa N’ Roll Records by Ismael Vazquez.
Bossa N’ Roll Records by Ismael Vazquez.
IsmaelVazquez38
 
CapTechTalks Webinar Slides June 2024 Donovan Wright.pptx
CapTechTalks Webinar Slides June 2024 Donovan Wright.pptxCapTechTalks Webinar Slides June 2024 Donovan Wright.pptx
CapTechTalks Webinar Slides June 2024 Donovan Wright.pptx
CapitolTechU
 
HYPERTENSION - SLIDE SHARE PRESENTATION.
HYPERTENSION - SLIDE SHARE PRESENTATION.HYPERTENSION - SLIDE SHARE PRESENTATION.
HYPERTENSION - SLIDE SHARE PRESENTATION.
deepaannamalai16
 
Wound healing PPT
Wound healing PPTWound healing PPT
Wound healing PPT
Jyoti Chand
 
The basics of sentences session 7pptx.pptx
The basics of sentences session 7pptx.pptxThe basics of sentences session 7pptx.pptx
The basics of sentences session 7pptx.pptx
heathfieldcps1
 
Educational Technology in the Health Sciences
Educational Technology in the Health SciencesEducational Technology in the Health Sciences
Educational Technology in the Health Sciences
Iris Thiele Isip-Tan
 
مصحف القراءات العشر أعد أحرف الخلاف سمير بسيوني.pdf
مصحف القراءات العشر   أعد أحرف الخلاف سمير بسيوني.pdfمصحف القراءات العشر   أعد أحرف الخلاف سمير بسيوني.pdf
مصحف القراءات العشر أعد أحرف الخلاف سمير بسيوني.pdf
سمير بسيوني
 
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptxPrésentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
siemaillard
 
Standardized tool for Intelligence test.
Standardized tool for Intelligence test.Standardized tool for Intelligence test.
Standardized tool for Intelligence test.
deepaannamalai16
 

Recently uploaded (20)

Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"
Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"
Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"
 
MDP on air pollution of class 8 year 2024-2025
MDP on air pollution of class 8 year 2024-2025MDP on air pollution of class 8 year 2024-2025
MDP on air pollution of class 8 year 2024-2025
 
Gender and Mental Health - Counselling and Family Therapy Applications and In...
Gender and Mental Health - Counselling and Family Therapy Applications and In...Gender and Mental Health - Counselling and Family Therapy Applications and In...
Gender and Mental Health - Counselling and Family Therapy Applications and In...
 
Pharmaceutics Pharmaceuticals best of brub
Pharmaceutics Pharmaceuticals best of brubPharmaceutics Pharmaceuticals best of brub
Pharmaceutics Pharmaceuticals best of brub
 
spot a liar (Haiqa 146).pptx Technical writhing and presentation skills
spot a liar (Haiqa 146).pptx Technical writhing and presentation skillsspot a liar (Haiqa 146).pptx Technical writhing and presentation skills
spot a liar (Haiqa 146).pptx Technical writhing and presentation skills
 
Elevate Your Nonprofit's Online Presence_ A Guide to Effective SEO Strategies...
Elevate Your Nonprofit's Online Presence_ A Guide to Effective SEO Strategies...Elevate Your Nonprofit's Online Presence_ A Guide to Effective SEO Strategies...
Elevate Your Nonprofit's Online Presence_ A Guide to Effective SEO Strategies...
 
CHUYÊN ĐỀ ÔN TẬP VÀ PHÁT TRIỂN CÂU HỎI TRONG ĐỀ MINH HỌA THI TỐT NGHIỆP THPT ...
CHUYÊN ĐỀ ÔN TẬP VÀ PHÁT TRIỂN CÂU HỎI TRONG ĐỀ MINH HỌA THI TỐT NGHIỆP THPT ...CHUYÊN ĐỀ ÔN TẬP VÀ PHÁT TRIỂN CÂU HỎI TRONG ĐỀ MINH HỌA THI TỐT NGHIỆP THPT ...
CHUYÊN ĐỀ ÔN TẬP VÀ PHÁT TRIỂN CÂU HỎI TRONG ĐỀ MINH HỌA THI TỐT NGHIỆP THPT ...
 
Oliver Asks for More by Charles Dickens (9)
Oliver Asks for More by Charles Dickens (9)Oliver Asks for More by Charles Dickens (9)
Oliver Asks for More by Charles Dickens (9)
 
Bonku-Babus-Friend by Sathyajith Ray (9)
Bonku-Babus-Friend by Sathyajith Ray  (9)Bonku-Babus-Friend by Sathyajith Ray  (9)
Bonku-Babus-Friend by Sathyajith Ray (9)
 
A Free 200-Page eBook ~ Brain and Mind Exercise.pptx
A Free 200-Page eBook ~ Brain and Mind Exercise.pptxA Free 200-Page eBook ~ Brain and Mind Exercise.pptx
A Free 200-Page eBook ~ Brain and Mind Exercise.pptx
 
Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...
Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...
Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...
 
Bossa N’ Roll Records by Ismael Vazquez.
Bossa N’ Roll Records by Ismael Vazquez.Bossa N’ Roll Records by Ismael Vazquez.
Bossa N’ Roll Records by Ismael Vazquez.
 
CapTechTalks Webinar Slides June 2024 Donovan Wright.pptx
CapTechTalks Webinar Slides June 2024 Donovan Wright.pptxCapTechTalks Webinar Slides June 2024 Donovan Wright.pptx
CapTechTalks Webinar Slides June 2024 Donovan Wright.pptx
 
HYPERTENSION - SLIDE SHARE PRESENTATION.
HYPERTENSION - SLIDE SHARE PRESENTATION.HYPERTENSION - SLIDE SHARE PRESENTATION.
HYPERTENSION - SLIDE SHARE PRESENTATION.
 
Wound healing PPT
Wound healing PPTWound healing PPT
Wound healing PPT
 
The basics of sentences session 7pptx.pptx
The basics of sentences session 7pptx.pptxThe basics of sentences session 7pptx.pptx
The basics of sentences session 7pptx.pptx
 
Educational Technology in the Health Sciences
Educational Technology in the Health SciencesEducational Technology in the Health Sciences
Educational Technology in the Health Sciences
 
مصحف القراءات العشر أعد أحرف الخلاف سمير بسيوني.pdf
مصحف القراءات العشر   أعد أحرف الخلاف سمير بسيوني.pdfمصحف القراءات العشر   أعد أحرف الخلاف سمير بسيوني.pdf
مصحف القراءات العشر أعد أحرف الخلاف سمير بسيوني.pdf
 
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptxPrésentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
 
Standardized tool for Intelligence test.
Standardized tool for Intelligence test.Standardized tool for Intelligence test.
Standardized tool for Intelligence test.
 

[ITP - Lecture 16] Structures in C/C++

  • 1. Structures Intro to Programming MUHAMMAD HAMMAD WASEEM 1 Why Use Structures We have seen earlier how ordinary variables can hold one piece of information and how arrays can hold a number of pieces of information of the same data type. These two data types can handle a great variety of situations. But quite often we deal with entities that are collection of dissimilar data types. For example, suppose you want to store data about a book. You might want to store its name (a string), its price (a float) and number of pages in it (an int). If data about say 3 such books is to be stored, then we can follow two approaches: a) Construct individual arrays, one for storing names, another for storing prices and still another for storing number of pages. b) Use a structure variable. A structure contains a number of data types grouped together. These data types may or may not be of the same type. The following example illustrates the use of this data type. main( ) { struct book { char name ; float price ; int pages ; } ; struct book b1, b2, b3 ; printf ( "nEnter names, prices & no. of pages of 3 booksn" ) ; scanf ( "%c %f %d", &b1.name, &b1.price, &b1.pages ) ; scanf ( "%c %f %d", &b2.name, &b2.price, &b2.pages ) ; scanf ( "%c %f %d", &b3.name, &b3.price, &b3.pages ) ; printf ( "nAnd this is what you entered" ) ; printf ( "n%c %f %d", b1.name, b1.price, b1.pages ) ; printf ( "n%c %f %d", b2.name, b2.price, b2.pages ) ; printf ( "n%c %f %d", b3.name, b3.price, b3.pages ) ; } And here is the output... Enter names, prices and no. of pages of 3 books A 100.00 354 C 256.50 682 F 233.70 512 Declaring a Structure In example program above, the following statement declares the structure type: struct book { char name ; float price ; int pages ; } ;
  • 2. Structures Intro to Programming MUHAMMAD HAMMAD WASEEM 2 This statement defines a new data type called struct book. Each variable of this data type will consist of a character variable called name, a float variable called price and an integer variable called pages. The general form of a structure declaration statement is given below: struct <structure name> { structure element 1 ; structure element 2 ; structure element 3 ; ...... ...... } ; Once the new structure data type has been defined one or more variables can be declared to be of that type. For example the variables b1, b2, b3 can be declared to be of the type struct book, as, struct book b1, b2, b3 ; If we so desire, we can combine the declaration of the structure type and the structure variables in one statement. For example, struct book { char name ; float price ; int pages ; } ; struct book b1, b2, b3 ; is same as... struct book { char name ; float price ; int pages ; } b1, b2, b3 ; or even... struct { char name ; float price ; int pages ; } b1, b2, b3 ; Like primary variables and arrays, structure variables can also be initialized where they are declared. The format used is quite similar to that used to initiate arrays. struct book { char name[10] ; float price ; int pages ; } ;
  • 3. Structures Intro to Programming MUHAMMAD HAMMAD WASEEM 3 struct book b1 = { "Basic", 130.00, 550 } ; struct book b2 = { "Physics", 150.80, 800 } ; Accessing Structure Elements In arrays we can access individual elements of an array using a subscript. Structures use a different scheme. They use a dot (.) operator. So to refer to pages of the structure defined in sample program we have to use, b1.pages Similarly, to refer to price we would use, b1.price Note that before the dot there must always be a structure variable and after the dot there must always be a structure element. How Structure Elements are Stored Whatever be the elements of a structure, they are always stored in contiguous memory locations. The following program would illustrate this: main( ) { struct book { char name ; float price ; int pages ; } ; struct book b1 = { 'B', 130.00, 550 } ; printf ( "nAddress of name = %u", &b1.name ) ; printf ( "nAddress of price = %u", &b1.price ) ; printf ( "nAddress of pages = %u", &b1.pages ) ; } Here is the output of the program... Address of name = 65518 Address of price = 65519 Address of pages = 65523 Actually the structure elements are stored in memory as shown in the Figure
  • 4. Structures Intro to Programming MUHAMMAD HAMMAD WASEEM 4 Array of Structures In this program, to store data of 100 books we would be required to use 100 different structure variables from b1 to b100, which is definitely not very convenient. A better approach would be to use an array of structures. Following program shows how to use an array of structures. main( ) { struct book { char name ; float price ; int pages ; } ; struct book b[100] ; int i ; for ( i = 0 ; i <= 99 ; i++ ) { printf ( "nEnter name, price and pages " ) ; scanf ( "%c %f %d", &b[i].name, &b[i].price, &b[i].pages ) ; } for ( i = 0 ; i <= 99 ; i++ ) printf ( "n%c %f %d", b[i].name, b[i].price, b[i].pages ); } linkfloat( ) { float a = 0, *b ; b = &a ; /* cause emulator to be linked */ a = *b ; /* suppress the warning - variable not used */ } Now a few explanations about the program: a) Notice how the array of structures is declared... struct book b[100] ; This provides space in memory for 100 structures of the type struct book. b) The syntax we use to reference each element of the array b is similar to the syntax used for arrays of ints and chars. For example, we refer to zeroth book’s price as b[0].price. Similarly, we refer first book’s pages as b[1].pages. c) It should be appreciated what careful thought Dennis Ritchie has put into C language. He first defined array as a collection of similar elements; then realized that dissimilar data types that are often found in real life cannot be handled using arrays, therefore created a new data type called structure. But even using structures programming convenience could not be achieved, because a lot of variables (b1 to b100 for storing data about hundred books) needed to be handled. Therefore he allowed us to create an array of structures; an array of similar data types which themselves are a collection of dissimilar data types. d) In an array of structures all elements of the array are stored in adjacent memory locations. Since each element of this array is a structure, and since all structure elements are always
  • 5. Structures Intro to Programming MUHAMMAD HAMMAD WASEEM 5 stored in adjacent locations you can very well visualise the arrangement of array of structures in memory. In our example, b[0]’s name, price and pages in memory would be immediately followed by b[1]’s name, price and pages, and so on. e) What is the function linkfloat( ) doing here? If you don’t define it you are bound to get the error "Floating Point Formats Not Linked" with majority of C Compilers. What causes this error to occur? When parsing our source file, if the compiler encounters a reference to the address of a float, it sets a flag to have the linker link in the floating-point emulator. A floating point emulator is used to manipulate floating point numbers in runtime library functions like scanf( ) and atof( ). There are some cases in which the reference to the float is a bit obscure and the compiler does not detect the need for the emulator. The most common is using scanf( ) to read a float in an array of structures as shown in our program. How can we force the formats to be linked? That’s where the linkfloat( ) function comes in. It forces linking of the floating-point emulator into an application. There is no need to call this function, just define it anywhere in your program. Uses of Structures Where are structures useful? The immediate application that comes to the mind is Database Management. That is, to maintain data about employees in an organization, books in a library, items in a store, financial accounting transactions in a company etc. But mind you, use of structures stretches much beyond database management. They can be used for a variety of purposes like: a) Changing the size of the cursor b) Clearing the contents of the screen c) Placing the cursor at an appropriate position on screen d) Drawing any graphics shape on the screen e) Receiving a key from the keyboard f) Checking the memory size of the computer g) Finding out the list of equipment attached to the computer h) Formatting a floppy i) Hiding a file from the directory j) Displaying the directory of a disk k) Sending the output to printer l) Interacting with the mouse And that is certainly a very impressive list! At least impressive enough to make you realize how important a data type a structure is and to be thorough with it if you intend to program any of the above applications.