SlideShare a Scribd company logo
Programming in C & Data Structures 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, GSKSJTI, Bengaluru Page 1
MODULE 4: Structures
STRUCTURES IN C:
Arrays are used to store large set of data and manipulate them but the disadvantage is that all
the elements stored in an array are to be of the same data type. If we need to use a collection of
different data type items it is not possible using an array.
When we require collection of data items of different data types, we can use a structure.
Structure is a method of packing data of different types. In general, structure is a collection of
data items of different data types. A Structure contains many elements each of same or
different data type.
A structure is a variable in which different types of data can be stored together with one
variable name. Consider the data a teacher might need for a student: Name, Class, GPA, test
scores, final score, etc. A structure data type called student can hold all this information
The above is a declaration of a data type called student. It is not a variable declaration, but a
type (template) declaration.
To actually declare a structure variable, the standard syntax is used:
struct student amar, Krishna, suma;
Structure members can be initialized at declaration. This is similar to the initialization of
arrays; the initial values are simply listed inside a pair of braces, with each value separated by
a comma.
What data type are allowed to structure members? Anything goes: basic types, arrays, strings,
pointers, even other structures. You can even make an array of structures.
General format of structure declaration in C:
struct tag_name // structure type (template) delcaration
{
data type member1; // elements of the structure
data type member2;
…
…
}; // semicolon required at the end of declaration
The closing bracket of structure type declaration must be followed by a semicolon. Usually
structure declaration appears at the top of the source code (before main).
Programming in C & Data Structures 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, GSKSJTI, Bengaluru Page 2
Example:
struct lib_books
{
char title[20];
char author[15];
int pages;
float price;
};
The keyword struct declares a structure to hold the details of four fields namely: title, author,
pages and price. The element of the structure are known members of the structure. Each
member may belong to different or same data type. The structure we just declared is not a
variable by itself but a template for the strcture.
Note: The members of a structure do not occupy memory until they are associated with a
structure variable. We can declare structure variables using the tag name anywhere in the
program. For example, the statement
struct lib_books book1, book2, book3;
declares book1,book2,book3 as variables of type struct lib_books. Each declaration, i.e, each
variable book1, book2, book3 consists of four members of the structure lib_books.
Memory Map of structure variable book1 is as shown. Each member of the structure is
allocated memory according to its type (int, char etc) and total memory allocated to variable
book1 is the “sum” of memory allocated to all its members.
book1.title book1.author book1.pages book1.price
book1
The complete structure declaration might look like this:
struct lib_books
{
char title[20]; // title, author etc are members of the structure
char author[15];
int pages;
float price;
}; // create a structure template with members
void main ( )
{
struct lib_books, book1, book2, book3; // create 3 structure type variables
….
}
We can also combine both template declaration and variables declaration in one statement as
shown here:
Programming in C & Data Structures 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, GSKSJTI, Bengaluru Page 3
struct lib_books
{
char title[20];
char author[15];
int pages;
float price;
} book1, book2, book3; // declare a structure template and create 3 variables
where, book1,book2,book3 are structure variables representing 3 books but does not include
a tag name for use in the declaration.
A structure is usually defined before main along with macro definitions. In such cases, the
structure assumes global status and all the functions can access the structure.
4.1 Accessing & initializing Structure Members:
The link between a structure member and a structure variable is established using the
member access operator ‘.’ which is known as dot operator and is used to access individual
structure element.
For example, we can access the member ‘price’ belonging to structure variable book1 as
book1. price.
 The assignment (=) operator can be used to give values to structure members.
book1.pages=250;
book1.price=28.50;
 We can also use scanf statement to assign values like
scanf(“%s”, book1.file);
scanf(“%d”, &book1.pages);
Consider another example:
struct student {
int id;
char name[10];
float avg ;
} a , b , c;
Here, we create a structure named “student” and define 3 variables a, b, c of type “student”.
The items id, name, avg are known as structure members.
a.id - refers to the member named “id” of the structure variable a.
scanf( “%d”, &a.id); this statement can accept an integer roll number of structure “a” from user.
e.g. struct book {
char name;
int pages;
float price;
}; // structure declaration
We can declare a structure variable (say z) and initialize as:
struct book z = { ‘s’, 125, 90.0};
Here, z.name is ‘s’. z.pages is 125 and z.price is 90.0
Programming in C & Data Structures 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, GSKSJTI, Bengaluru Page 4
/* Example program using structures */
#include<stdio.h>
struct student
{
int id_no;
char name[20];
char address[20];
int age;
} s1;
void main( )
{
printf("Enter the student information");
printf("Now Enter the student id_no");
scanf("%d", &s1.id_no);
printf("Enter the name of the student");
scanf("%s", s1.name);
printf("Enter the address of the student");
scanf("%s", &s1.address);
printf("Enter the age of the student");
scanf("%d", &s1.age);
printf("Student informationn");
printf("student id_number=%dn", s1.id_no);
printf("student name=%sn", s1.name);
printf("student Address=%sn", s1.address);
printf("Age of student=%dn", s1.age);
}
Programming in C & Data Structures 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, GSKSJTI, Bengaluru Page 5
Programming in C & Data Structures 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, GSKSJTI, Bengaluru Page 6
4.2 Array of Structures:
It is possible to define an array of structures. For example, if we are maintaining information of
all the students in the college and if 100 students are studying in the college, then we need to
use an array than single structure variables. We can define an array of structures as shown in
the following example:
struct
{
int id_no;
char name[20];
char address[20];
int age;
}
student[100];
An array of structures can be assigned initial values just as any other array. Remember that
each element is a structure that must be assigned corresponding initial values as illustrated
below.
#include<stdio.h>
struct student // structure type declaration
{
int id_no; // 4 data members in the structure
char name[20];
char address[20];
int age;
}stu[100]; // create 100 variables of structure student
// i.e., array of structures just like array of 100 integers
void main( )
{
int k, n;
printf("Enter the number of students");
scanf("%d",&n);
printf(" Enter Id_no,name address & age of students n");
for(k=0;k<n; k++)
scanf ("%d %s %s %d", &stu[k].id_no, stu[k].name, stu [k].address, &stu[k].age);
printf("n Student information details are: ");
for (k=0;k< n;k++)
printf("%d %s %s %d n", stu[k].id_no, stu[k].name, stu [k].address, stu[k].age);
} // end of main
Programming in C & Data Structures 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, GSKSJTI, Bengaluru Page 7
4.3 Structure within a structure (Nested Structures)
A structure may be defined as a member of another structure. In such contexts, the declaration
of the embedded structure must appear before the declarations of other structures.
Ex:
struct date
{
int day;
int month;
int year;
};
struct student
{
int id_no;
char name[20];
char address[20];
int age;
struct date doa; // “date” is a structure defined earlier
struct date dob;
} oldstudent, newstudent;
the structure student contains another structure date as its one of its members.
As mentioned earlier, structures can have other structures as members. Say you wanted to
make a structure that contained both date and time information. One way to accomplish this
Programming in C & Data Structures 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, GSKSJTI, Bengaluru Page 8
would be to combine two separate structures; one for the date and one for the time. For
example,
struct date {
int month;
int day;
int year; };
struct time {
int hour;
int min;
int sec; };
struct new_date {
struct date today;
struct time now; };
• here, “new_date” a structure whose elements (members) are nothing but two other
previously declared structures.
4.4. Structures as Function Arguments:
We can pass structures as arguments to functions. Unlike array names however, which always
point to the start of the array, structure names are not pointers. As a result, when we change
structure parameter inside a function, we don’t effect its corresponding argument. i.e., the
structure is “passed by value”; so, actual arguments in the calling function are not modified.
a) Passing structure elements to functions:
A structure may be passed into a function as individual member or a separate variable.
A program example to display the contents of a structure passing the individual elements to a
function is shown below.
#include<stdio.h>
struct emp // structure declaration
{
int emp_id; // structure members
char name[25];
char department[10];
float salary;
};
void display(int, char [ ]); // function declaration
void main( )
{
static struct emp emp1={125,"RAMESH", "ECE", 50000.00};
display(emp1.emp_id, emp1.name); // function call with two members of the structure
// passed to function as individual variables
} // end of main
/* function to display structure member values */
void display(int e_no, char e_name[ ])
{
printf("%d %s", e_no, e_name);
}
Programming in C & Data Structures 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, GSKSJTI, Bengaluru Page 9
b) Passing entire structure as argument to a function
#include<stdio.h>
struct dob // structure declaration
{
short int dd, mm, yy; // structure members
};
void display (struct dob d) ;// function declaration with structure as argument
void main( )
{
struct dob d1; // creating structure variable d1 of type dob
printf (“n enter your date of birth as date, month & year n”);
scanf (“%d %d %d” , &d1.dd, &d1.mm, &d1.yy);
display(d1); // function call with structure as argument
} // end of main
/* function to display structure member values */
void display(struct date x)
{
printf (" Your date of birth is : n”);
printf (“%d - %d - %d", x.dd, x.mm. x.yy);
}
4.5 Pointers to Structures:
One can have pointer variable that contain the address of complete structures, just like with
the basic data types. Structure pointers are declared and used in the same manner as “simple”
pointers.
In C, there is a special symbol -> which is used as a shorthand when working with pointers to
structures. It is officially called the structure pointer operator (arrow operator). Its syntax is
struct_ptr->member
Note:
*(struct_ptr).member is same as struct_ptr->member
Ex:
struct student {
int id;
char *name;
} stu1, stu2 ; // create 2 variables stu1 and stu2 of type struct student
void main ( )
{
struct student *stp; // stp is a pointer variable
stp = &stu1; // stp holds the address of stu1 i.e., stp “points” to stu1
// initializing structure members using pointer variable and dot operator
(*stp).id=38; // same as stu1.id = 38;
(*stp).name="Ramya";
• Thus, the last two lines of this example could also have been written as:
stp->id=38;
stp->name="Ramya";

More Related Content

What's hot

Database Design and Normalization Techniques
Database Design and Normalization TechniquesDatabase Design and Normalization Techniques
Database Design and Normalization Techniques
Nishant Munjal
 
Structure in c language
Structure in c languageStructure in c language
Structure in c language
sangrampatil81
 
Unit4 C
Unit4 C Unit4 C
Unit4 C
arnold 7490
 
Object oriented database concepts
Object oriented database conceptsObject oriented database concepts
Object oriented database concepts
Temesgenthanks
 
Basic of Structure,Structure members,Accessing Structure member,Nested Struct...
Basic of Structure,Structure members,Accessing Structure member,Nested Struct...Basic of Structure,Structure members,Accessing Structure member,Nested Struct...
Basic of Structure,Structure members,Accessing Structure member,Nested Struct...
Smit Shah
 
When to use a structure vs classes in c++
When to use a structure vs classes in c++When to use a structure vs classes in c++
When to use a structure vs classes in c++
Naman Kumar
 
Module 5 oodb systems semantic db systems
Module 5 oodb systems  semantic db systemsModule 5 oodb systems  semantic db systems
Module 5 oodb systems semantic db systems
Taher Barodawala
 
Introduction to odbms
Introduction to odbmsIntroduction to odbms
Introduction to odbms
ajay pashankar
 
Structure in c
Structure in cStructure in c
Structure in C
Structure in CStructure in C
Structure in C
Kamal Acharya
 
Structures in c++
Structures in c++Structures in c++
Structures in c++
Swarup Kumar Boro
 
Chapt 1 odbms
Chapt 1 odbmsChapt 1 odbms
Chapt 1 odbms
Sushil Kulkarni
 
Object Oriented Dbms
Object Oriented DbmsObject Oriented Dbms
Object Oriented Dbms
maryeem
 
Oodbms ch 20
Oodbms ch 20Oodbms ch 20
Oodbms ch 20
saurabhshertukde
 
17 structure-and-union
17 structure-and-union17 structure-and-union
17 structure-and-union
Rohit Shrivastava
 
08. Object Oriented Database in DBMS
08. Object Oriented Database in DBMS08. Object Oriented Database in DBMS
08. Object Oriented Database in DBMS
koolkampus
 
Object oriented database
Object oriented databaseObject oriented database
Object oriented database
Md. Hasan Imam Bijoy
 
Structure & union
Structure & unionStructure & union
Structure & union
Rupesh Mishra
 
CPU : Structures And Unions
CPU : Structures And UnionsCPU : Structures And Unions
CPU : Structures And Unions
Dhrumil Patel
 
Chapter 13.1.9
Chapter 13.1.9Chapter 13.1.9
Chapter 13.1.9
patcha535
 

What's hot (20)

Database Design and Normalization Techniques
Database Design and Normalization TechniquesDatabase Design and Normalization Techniques
Database Design and Normalization Techniques
 
Structure in c language
Structure in c languageStructure in c language
Structure in c language
 
Unit4 C
Unit4 C Unit4 C
Unit4 C
 
Object oriented database concepts
Object oriented database conceptsObject oriented database concepts
Object oriented database concepts
 
Basic of Structure,Structure members,Accessing Structure member,Nested Struct...
Basic of Structure,Structure members,Accessing Structure member,Nested Struct...Basic of Structure,Structure members,Accessing Structure member,Nested Struct...
Basic of Structure,Structure members,Accessing Structure member,Nested Struct...
 
When to use a structure vs classes in c++
When to use a structure vs classes in c++When to use a structure vs classes in c++
When to use a structure vs classes in c++
 
Module 5 oodb systems semantic db systems
Module 5 oodb systems  semantic db systemsModule 5 oodb systems  semantic db systems
Module 5 oodb systems semantic db systems
 
Introduction to odbms
Introduction to odbmsIntroduction to odbms
Introduction to odbms
 
Structure in c
Structure in cStructure in c
Structure in c
 
Structure in C
Structure in CStructure in C
Structure in C
 
Structures in c++
Structures in c++Structures in c++
Structures in c++
 
Chapt 1 odbms
Chapt 1 odbmsChapt 1 odbms
Chapt 1 odbms
 
Object Oriented Dbms
Object Oriented DbmsObject Oriented Dbms
Object Oriented Dbms
 
Oodbms ch 20
Oodbms ch 20Oodbms ch 20
Oodbms ch 20
 
17 structure-and-union
17 structure-and-union17 structure-and-union
17 structure-and-union
 
08. Object Oriented Database in DBMS
08. Object Oriented Database in DBMS08. Object Oriented Database in DBMS
08. Object Oriented Database in DBMS
 
Object oriented database
Object oriented databaseObject oriented database
Object oriented database
 
Structure & union
Structure & unionStructure & union
Structure & union
 
CPU : Structures And Unions
CPU : Structures And UnionsCPU : Structures And Unions
CPU : Structures And Unions
 
Chapter 13.1.9
Chapter 13.1.9Chapter 13.1.9
Chapter 13.1.9
 

Similar to Lk module4 structures

C structure and union
C structure and unionC structure and union
C structure and union
Thesis Scientist Private Limited
 
Structures in c++
Structures in c++Structures in c++
Structures in c++
Swarup Boro
 
Chapter4.pptx
Chapter4.pptxChapter4.pptx
Chapter4.pptx
WondimuBantihun1
 
STRUCTURE AND UNION IN C MRS.SOWMYA JYOTHI.pdf
STRUCTURE AND UNION IN C MRS.SOWMYA JYOTHI.pdfSTRUCTURE AND UNION IN C MRS.SOWMYA JYOTHI.pdf
STRUCTURE AND UNION IN C MRS.SOWMYA JYOTHI.pdf
SowmyaJyothi3
 
C UNIT-4 PREPARED BY M V BRAHMANANDA RE
C UNIT-4 PREPARED BY M V BRAHMANANDA REC UNIT-4 PREPARED BY M V BRAHMANANDA RE
C UNIT-4 PREPARED BY M V BRAHMANANDA RE
Rajeshkumar Reddy
 
Unit-V.pptx
Unit-V.pptxUnit-V.pptx
Unit-V.pptx
Mehul Desai
 
Structure & union
Structure & unionStructure & union
Structure & union
lalithambiga kamaraj
 
Structures
StructuresStructures
Structures
DrJasmineBeulahG
 
CP Handout#10
CP Handout#10CP Handout#10
CP Handout#10
trupti1976
 
Chapter15 structure
Chapter15 structureChapter15 structure
Chapter15 structure
Deepak Singh
 
Structures
StructuresStructures
Structures
archikabhatia
 
Structures in c language
Structures in c languageStructures in c language
Structures in c language
Tanmay Modi
 
Structures in c language
Structures in c languageStructures in c language
Structures in c language
tanmaymodi4
 
2 lesson 2 object oriented programming in c++
2 lesson 2 object oriented programming in c++2 lesson 2 object oriented programming in c++
2 lesson 2 object oriented programming in c++
Jeff TUYISHIME
 
data structure and c programing concepts
data structure and c programing conceptsdata structure and c programing concepts
data structure and c programing concepts
kavitham66441
 
Programming in C
Programming in CProgramming in C
Programming in C
MalathiNagarajan20
 
Revision notes for exam 2011 computer science with C++
Revision notes for exam 2011 computer science with C++Revision notes for exam 2011 computer science with C++
Revision notes for exam 2011 computer science with C++
Deepak Singh
 
Structure prespentation
Structure prespentation Structure prespentation
Structure prespentation
ashu awais
 
structure.ppt
structure.pptstructure.ppt
structure.ppt
Sheik Mohideen
 
structures_v1.ppt
structures_v1.pptstructures_v1.ppt
structures_v1.ppt
ansariparveen06
 

Similar to Lk module4 structures (20)

C structure and union
C structure and unionC structure and union
C structure and union
 
Structures in c++
Structures in c++Structures in c++
Structures in c++
 
Chapter4.pptx
Chapter4.pptxChapter4.pptx
Chapter4.pptx
 
STRUCTURE AND UNION IN C MRS.SOWMYA JYOTHI.pdf
STRUCTURE AND UNION IN C MRS.SOWMYA JYOTHI.pdfSTRUCTURE AND UNION IN C MRS.SOWMYA JYOTHI.pdf
STRUCTURE AND UNION IN C MRS.SOWMYA JYOTHI.pdf
 
C UNIT-4 PREPARED BY M V BRAHMANANDA RE
C UNIT-4 PREPARED BY M V BRAHMANANDA REC UNIT-4 PREPARED BY M V BRAHMANANDA RE
C UNIT-4 PREPARED BY M V BRAHMANANDA RE
 
Unit-V.pptx
Unit-V.pptxUnit-V.pptx
Unit-V.pptx
 
Structure & union
Structure & unionStructure & union
Structure & union
 
Structures
StructuresStructures
Structures
 
CP Handout#10
CP Handout#10CP Handout#10
CP Handout#10
 
Chapter15 structure
Chapter15 structureChapter15 structure
Chapter15 structure
 
Structures
StructuresStructures
Structures
 
Structures in c language
Structures in c languageStructures in c language
Structures in c language
 
Structures in c language
Structures in c languageStructures in c language
Structures in c language
 
2 lesson 2 object oriented programming in c++
2 lesson 2 object oriented programming in c++2 lesson 2 object oriented programming in c++
2 lesson 2 object oriented programming in c++
 
data structure and c programing concepts
data structure and c programing conceptsdata structure and c programing concepts
data structure and c programing concepts
 
Programming in C
Programming in CProgramming in C
Programming in C
 
Revision notes for exam 2011 computer science with C++
Revision notes for exam 2011 computer science with C++Revision notes for exam 2011 computer science with C++
Revision notes for exam 2011 computer science with C++
 
Structure prespentation
Structure prespentation Structure prespentation
Structure prespentation
 
structure.ppt
structure.pptstructure.ppt
structure.ppt
 
structures_v1.ppt
structures_v1.pptstructures_v1.ppt
structures_v1.ppt
 

More from Krishna Nanda

Python regular expressions
Python regular expressionsPython regular expressions
Python regular expressions
Krishna Nanda
 
Python dictionaries
Python dictionariesPython dictionaries
Python dictionaries
Krishna Nanda
 
Python lists
Python listsPython lists
Python lists
Krishna Nanda
 
Python-Tuples
Python-TuplesPython-Tuples
Python-Tuples
Krishna Nanda
 
Python- strings
Python- stringsPython- strings
Python- strings
Krishna Nanda
 
Python-files
Python-filesPython-files
Python-files
Krishna Nanda
 
Computer Communication Networks- Introduction to Transport layer
Computer Communication Networks- Introduction to Transport layerComputer Communication Networks- Introduction to Transport layer
Computer Communication Networks- Introduction to Transport layer
Krishna Nanda
 
Computer Communication Networks- TRANSPORT LAYER PROTOCOLS
Computer Communication Networks- TRANSPORT LAYER PROTOCOLSComputer Communication Networks- TRANSPORT LAYER PROTOCOLS
Computer Communication Networks- TRANSPORT LAYER PROTOCOLS
Krishna Nanda
 
COMPUTER COMMUNICATION NETWORKS -IPv4
COMPUTER COMMUNICATION NETWORKS -IPv4COMPUTER COMMUNICATION NETWORKS -IPv4
COMPUTER COMMUNICATION NETWORKS -IPv4
Krishna Nanda
 
COMPUTER COMMUNICATION NETWORKS-R-Routing protocols 2
COMPUTER COMMUNICATION NETWORKS-R-Routing protocols 2COMPUTER COMMUNICATION NETWORKS-R-Routing protocols 2
COMPUTER COMMUNICATION NETWORKS-R-Routing protocols 2
Krishna Nanda
 
Computer Communication Networks-Routing protocols 1
Computer Communication Networks-Routing protocols 1Computer Communication Networks-Routing protocols 1
Computer Communication Networks-Routing protocols 1
Krishna Nanda
 
Computer Communication Networks-Wireless LAN
Computer Communication Networks-Wireless LANComputer Communication Networks-Wireless LAN
Computer Communication Networks-Wireless LAN
Krishna Nanda
 
Computer Communication Networks-Network Layer
Computer Communication Networks-Network LayerComputer Communication Networks-Network Layer
Computer Communication Networks-Network Layer
Krishna Nanda
 
Lk module3
Lk module3Lk module3
Lk module3
Krishna Nanda
 
Lk module4 file
Lk module4 fileLk module4 file
Lk module4 file
Krishna Nanda
 
Lk module5 pointers
Lk module5 pointersLk module5 pointers
Lk module5 pointers
Krishna Nanda
 

More from Krishna Nanda (16)

Python regular expressions
Python regular expressionsPython regular expressions
Python regular expressions
 
Python dictionaries
Python dictionariesPython dictionaries
Python dictionaries
 
Python lists
Python listsPython lists
Python lists
 
Python-Tuples
Python-TuplesPython-Tuples
Python-Tuples
 
Python- strings
Python- stringsPython- strings
Python- strings
 
Python-files
Python-filesPython-files
Python-files
 
Computer Communication Networks- Introduction to Transport layer
Computer Communication Networks- Introduction to Transport layerComputer Communication Networks- Introduction to Transport layer
Computer Communication Networks- Introduction to Transport layer
 
Computer Communication Networks- TRANSPORT LAYER PROTOCOLS
Computer Communication Networks- TRANSPORT LAYER PROTOCOLSComputer Communication Networks- TRANSPORT LAYER PROTOCOLS
Computer Communication Networks- TRANSPORT LAYER PROTOCOLS
 
COMPUTER COMMUNICATION NETWORKS -IPv4
COMPUTER COMMUNICATION NETWORKS -IPv4COMPUTER COMMUNICATION NETWORKS -IPv4
COMPUTER COMMUNICATION NETWORKS -IPv4
 
COMPUTER COMMUNICATION NETWORKS-R-Routing protocols 2
COMPUTER COMMUNICATION NETWORKS-R-Routing protocols 2COMPUTER COMMUNICATION NETWORKS-R-Routing protocols 2
COMPUTER COMMUNICATION NETWORKS-R-Routing protocols 2
 
Computer Communication Networks-Routing protocols 1
Computer Communication Networks-Routing protocols 1Computer Communication Networks-Routing protocols 1
Computer Communication Networks-Routing protocols 1
 
Computer Communication Networks-Wireless LAN
Computer Communication Networks-Wireless LANComputer Communication Networks-Wireless LAN
Computer Communication Networks-Wireless LAN
 
Computer Communication Networks-Network Layer
Computer Communication Networks-Network LayerComputer Communication Networks-Network Layer
Computer Communication Networks-Network Layer
 
Lk module3
Lk module3Lk module3
Lk module3
 
Lk module4 file
Lk module4 fileLk module4 file
Lk module4 file
 
Lk module5 pointers
Lk module5 pointersLk module5 pointers
Lk module5 pointers
 

Recently uploaded

The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
heathfieldcps1
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
adhitya5119
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
Nicholas Montgomery
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
WaniBasim
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
Colégio Santa Teresinha
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
chanes7
 
Smart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICTSmart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICT
simonomuemu
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
RitikBhardwaj56
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
Academy of Science of South Africa
 
Life upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for studentLife upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for student
NgcHiNguyn25
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
Israel Genealogy Research Association
 
How to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRMHow to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRM
Celine George
 
How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
Celine George
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
amberjdewit93
 
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
IreneSebastianRueco1
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
thanhdowork
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
Priyankaranawat4
 
How to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold MethodHow to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold Method
Celine George
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
ak6969907
 

Recently uploaded (20)

The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
 
Smart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICTSmart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICT
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
 
Life upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for studentLife upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for student
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
 
How to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRMHow to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRM
 
How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
 
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
 
How to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold MethodHow to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold Method
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
 

Lk module4 structures

  • 1. Programming in C & Data Structures 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, GSKSJTI, Bengaluru Page 1 MODULE 4: Structures STRUCTURES IN C: Arrays are used to store large set of data and manipulate them but the disadvantage is that all the elements stored in an array are to be of the same data type. If we need to use a collection of different data type items it is not possible using an array. When we require collection of data items of different data types, we can use a structure. Structure is a method of packing data of different types. In general, structure is a collection of data items of different data types. A Structure contains many elements each of same or different data type. A structure is a variable in which different types of data can be stored together with one variable name. Consider the data a teacher might need for a student: Name, Class, GPA, test scores, final score, etc. A structure data type called student can hold all this information The above is a declaration of a data type called student. It is not a variable declaration, but a type (template) declaration. To actually declare a structure variable, the standard syntax is used: struct student amar, Krishna, suma; Structure members can be initialized at declaration. This is similar to the initialization of arrays; the initial values are simply listed inside a pair of braces, with each value separated by a comma. What data type are allowed to structure members? Anything goes: basic types, arrays, strings, pointers, even other structures. You can even make an array of structures. General format of structure declaration in C: struct tag_name // structure type (template) delcaration { data type member1; // elements of the structure data type member2; … … }; // semicolon required at the end of declaration The closing bracket of structure type declaration must be followed by a semicolon. Usually structure declaration appears at the top of the source code (before main).
  • 2. Programming in C & Data Structures 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, GSKSJTI, Bengaluru Page 2 Example: struct lib_books { char title[20]; char author[15]; int pages; float price; }; The keyword struct declares a structure to hold the details of four fields namely: title, author, pages and price. The element of the structure are known members of the structure. Each member may belong to different or same data type. The structure we just declared is not a variable by itself but a template for the strcture. Note: The members of a structure do not occupy memory until they are associated with a structure variable. We can declare structure variables using the tag name anywhere in the program. For example, the statement struct lib_books book1, book2, book3; declares book1,book2,book3 as variables of type struct lib_books. Each declaration, i.e, each variable book1, book2, book3 consists of four members of the structure lib_books. Memory Map of structure variable book1 is as shown. Each member of the structure is allocated memory according to its type (int, char etc) and total memory allocated to variable book1 is the “sum” of memory allocated to all its members. book1.title book1.author book1.pages book1.price book1 The complete structure declaration might look like this: struct lib_books { char title[20]; // title, author etc are members of the structure char author[15]; int pages; float price; }; // create a structure template with members void main ( ) { struct lib_books, book1, book2, book3; // create 3 structure type variables …. } We can also combine both template declaration and variables declaration in one statement as shown here:
  • 3. Programming in C & Data Structures 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, GSKSJTI, Bengaluru Page 3 struct lib_books { char title[20]; char author[15]; int pages; float price; } book1, book2, book3; // declare a structure template and create 3 variables where, book1,book2,book3 are structure variables representing 3 books but does not include a tag name for use in the declaration. A structure is usually defined before main along with macro definitions. In such cases, the structure assumes global status and all the functions can access the structure. 4.1 Accessing & initializing Structure Members: The link between a structure member and a structure variable is established using the member access operator ‘.’ which is known as dot operator and is used to access individual structure element. For example, we can access the member ‘price’ belonging to structure variable book1 as book1. price.  The assignment (=) operator can be used to give values to structure members. book1.pages=250; book1.price=28.50;  We can also use scanf statement to assign values like scanf(“%s”, book1.file); scanf(“%d”, &book1.pages); Consider another example: struct student { int id; char name[10]; float avg ; } a , b , c; Here, we create a structure named “student” and define 3 variables a, b, c of type “student”. The items id, name, avg are known as structure members. a.id - refers to the member named “id” of the structure variable a. scanf( “%d”, &a.id); this statement can accept an integer roll number of structure “a” from user. e.g. struct book { char name; int pages; float price; }; // structure declaration We can declare a structure variable (say z) and initialize as: struct book z = { ‘s’, 125, 90.0}; Here, z.name is ‘s’. z.pages is 125 and z.price is 90.0
  • 4. Programming in C & Data Structures 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, GSKSJTI, Bengaluru Page 4 /* Example program using structures */ #include<stdio.h> struct student { int id_no; char name[20]; char address[20]; int age; } s1; void main( ) { printf("Enter the student information"); printf("Now Enter the student id_no"); scanf("%d", &s1.id_no); printf("Enter the name of the student"); scanf("%s", s1.name); printf("Enter the address of the student"); scanf("%s", &s1.address); printf("Enter the age of the student"); scanf("%d", &s1.age); printf("Student informationn"); printf("student id_number=%dn", s1.id_no); printf("student name=%sn", s1.name); printf("student Address=%sn", s1.address); printf("Age of student=%dn", s1.age); }
  • 5. Programming in C & Data Structures 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, GSKSJTI, Bengaluru Page 5
  • 6. Programming in C & Data Structures 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, GSKSJTI, Bengaluru Page 6 4.2 Array of Structures: It is possible to define an array of structures. For example, if we are maintaining information of all the students in the college and if 100 students are studying in the college, then we need to use an array than single structure variables. We can define an array of structures as shown in the following example: struct { int id_no; char name[20]; char address[20]; int age; } student[100]; An array of structures can be assigned initial values just as any other array. Remember that each element is a structure that must be assigned corresponding initial values as illustrated below. #include<stdio.h> struct student // structure type declaration { int id_no; // 4 data members in the structure char name[20]; char address[20]; int age; }stu[100]; // create 100 variables of structure student // i.e., array of structures just like array of 100 integers void main( ) { int k, n; printf("Enter the number of students"); scanf("%d",&n); printf(" Enter Id_no,name address & age of students n"); for(k=0;k<n; k++) scanf ("%d %s %s %d", &stu[k].id_no, stu[k].name, stu [k].address, &stu[k].age); printf("n Student information details are: "); for (k=0;k< n;k++) printf("%d %s %s %d n", stu[k].id_no, stu[k].name, stu [k].address, stu[k].age); } // end of main
  • 7. Programming in C & Data Structures 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, GSKSJTI, Bengaluru Page 7 4.3 Structure within a structure (Nested Structures) A structure may be defined as a member of another structure. In such contexts, the declaration of the embedded structure must appear before the declarations of other structures. Ex: struct date { int day; int month; int year; }; struct student { int id_no; char name[20]; char address[20]; int age; struct date doa; // “date” is a structure defined earlier struct date dob; } oldstudent, newstudent; the structure student contains another structure date as its one of its members. As mentioned earlier, structures can have other structures as members. Say you wanted to make a structure that contained both date and time information. One way to accomplish this
  • 8. Programming in C & Data Structures 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, GSKSJTI, Bengaluru Page 8 would be to combine two separate structures; one for the date and one for the time. For example, struct date { int month; int day; int year; }; struct time { int hour; int min; int sec; }; struct new_date { struct date today; struct time now; }; • here, “new_date” a structure whose elements (members) are nothing but two other previously declared structures. 4.4. Structures as Function Arguments: We can pass structures as arguments to functions. Unlike array names however, which always point to the start of the array, structure names are not pointers. As a result, when we change structure parameter inside a function, we don’t effect its corresponding argument. i.e., the structure is “passed by value”; so, actual arguments in the calling function are not modified. a) Passing structure elements to functions: A structure may be passed into a function as individual member or a separate variable. A program example to display the contents of a structure passing the individual elements to a function is shown below. #include<stdio.h> struct emp // structure declaration { int emp_id; // structure members char name[25]; char department[10]; float salary; }; void display(int, char [ ]); // function declaration void main( ) { static struct emp emp1={125,"RAMESH", "ECE", 50000.00}; display(emp1.emp_id, emp1.name); // function call with two members of the structure // passed to function as individual variables } // end of main /* function to display structure member values */ void display(int e_no, char e_name[ ]) { printf("%d %s", e_no, e_name); }
  • 9. Programming in C & Data Structures 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, GSKSJTI, Bengaluru Page 9 b) Passing entire structure as argument to a function #include<stdio.h> struct dob // structure declaration { short int dd, mm, yy; // structure members }; void display (struct dob d) ;// function declaration with structure as argument void main( ) { struct dob d1; // creating structure variable d1 of type dob printf (“n enter your date of birth as date, month & year n”); scanf (“%d %d %d” , &d1.dd, &d1.mm, &d1.yy); display(d1); // function call with structure as argument } // end of main /* function to display structure member values */ void display(struct date x) { printf (" Your date of birth is : n”); printf (“%d - %d - %d", x.dd, x.mm. x.yy); } 4.5 Pointers to Structures: One can have pointer variable that contain the address of complete structures, just like with the basic data types. Structure pointers are declared and used in the same manner as “simple” pointers. In C, there is a special symbol -> which is used as a shorthand when working with pointers to structures. It is officially called the structure pointer operator (arrow operator). Its syntax is struct_ptr->member Note: *(struct_ptr).member is same as struct_ptr->member Ex: struct student { int id; char *name; } stu1, stu2 ; // create 2 variables stu1 and stu2 of type struct student void main ( ) { struct student *stp; // stp is a pointer variable stp = &stu1; // stp holds the address of stu1 i.e., stp “points” to stu1 // initializing structure members using pointer variable and dot operator (*stp).id=38; // same as stu1.id = 38; (*stp).name="Ramya"; • Thus, the last two lines of this example could also have been written as: stp->id=38; stp->name="Ramya";