SlideShare a Scribd company logo
Unit-II
Structures
Unit-II(Structures)
 Introduction to Structures
 Definition
 Initialization of Structures
 Accessing structure members
 Nested Structures
 Array of Structures
 Structures and Functions
 Unions
 Typedef
 Enumerated Data types.
Introduction to Structures:
 Definition :Structure is a collection of
heterogeneous data elements.
 Structure is a user-defined datatype in C
language which allows us to combine data of
different data types.
 structures we can combine various data types to
store a specific type of data.
 Structures are used to represent a record
 Structure helps to construct a complex data type
which is more meaningful.
Example 1:
 I want to keep track of your books in a library.
You might want to track the following attributes
about each book −
 Title
 Author
 Subject
 cast
Example 2:
 If I want to write a program to store Student
information.
Student's name
age
branch
permanent address
father's name ….etc
 which included different data types( string
values, integer values etc).
 In structure, data is stored in form of records.
Defining a Structure
 To define a structure, you must use
the struct statement.
 The struct statement defines a new data type, with
more than one member.
 Syntax:
struct structure_name(or)structure tag
{
//member variable 1 ;
//member variable 2;
//member variable 3;
...
};
Defining a Structure
Syntax:
struct structure tag(or)structure name
{
member definition;
member definition;
...
member definition;
} [one or more structure variables];
 The structure tag is optional .
Each member definition is a normal variable definition,
(int i; or float f; or any other valid variable definition.)
EX:
Struct student_detail
{
char studentname[20];
int age;
int rollno;
float intermarks;
char address[20];
};
 we start with the struct keyword.
 we have to mention all the member variables,
which are nothing but normal C language
variables of different types like int, float, array
etc.
 Note: The closing curly brace in the structure
type declaration must be followed by a
semicolon(;).
Example of Structure
struct student_name
{
char studentname[20];
int age;
char branch[20] ;
char gender[10];
};
Here,
 struct Student name declares a structure to hold the details of a
studentdetails .
 which consists of 4 data fields,
namely name, age, branch and gender.
 These fields are called structure elements or members of
structures.
Example of Structure:
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
} book;
book is the name of the structure and is called as
the structure tag.
 Note: Structure members cannot be initialized
during structure definition time.
 Structure name is new data type name…not a
variable
 int a=10
Declaring Structure Variables
 It is possible to declare variables of a structure, either
along with structure definition or after the structure is
defined.
 Structure variable declaration is similar to the
declaration of any normal variable of any other datatype.
 Structure variables can be declared in following two
ways:
1. Declaring Structure variables separately
2. Declaring Structure variables along with structure
definition
Declaring Structure variables separately:
 Syntax:
struct structurename var1,var2…;
struct Student
{
int rollno;
char name[25];
float percentage;
};
struct Student s1, s2;
//declaring variables of struct Student
the above statement can be used in any function in a program
//s1 , s2 will local variables in the function
Declaring Structure variables with
structure definition
struct Student
{
int rollno;
char name[25];
float percentage;
}s1,s2;
//s1 and s2 are global variables
Here ,S1 and S2 are variables of structure Student.
However this approach is not much recommended.
Access members of a structure
 There are two types of operators used for
accessing members of a structure.
1. (.) Member operator(dot operator)
2. (-> ) Structure pointer operator(arrow
operator)
Ex:
 you want to access the salary of person2. Here's
how you can do it.
person2.salary
Access members of a structure
 (.) Member operator(dot operator):
 This operator can be used to access structure
members with structure variables..
 Syntax:
structurevariable. structuremember;
struct student s;
Ex:
s.rollno;
s.name;
s.percentage;
dot operator(program)
#include<stdio.h>
#include<string.h>
struct Student
{
int rollno;
char name[25];
float percentage;
};
void main()
{
struct Student s;
s.rollno= 18;
s.percentage = 93.23;
strcpy(s.name, "sita");
printf("Rollno of Student 1: %dn", s.rollno);
printf("Name of Student 1: %sn", s.name);
printf("percentage of student 1: %fn", s.percentage); }
#include <stdio.h>
#include <string.h>
struct Books
{ char title[50];
char author[50];
char subject[100];
int book_id;
};
int main( )
{
struct Books Book1; /* Declare Book1 of type Book */
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;
/* print Book1 info */
printf( "Book 1 title : %sn", Book1.title);
printf( "Book 1 author : %sn", Book1.author);
printf( "Book 1 subject : %sn", Book1.subject);
printf( "Book 1 book_id : %dn", Book1.book_id);
return 0;
}
Structure pointer operator(->arrow operator)
 This operator can be used to access structure
members with structure pointer variables.
 Syntax:
structure pointervariable-
>structuremember;
 struct student *p; //memory should create for
pointer variables using malloc
 p=(struct student *)malloc(sizeof(struct
student));
 Ex: p->rollno, p->name, p->percentage
 s.rollno,s.name,s.perc
 Structure members can be accessed and assigned
values in a number of ways.
 Structure members have no meaning individually
without the structure variables.
 Rollno,name,percentage --- no meaning(normal
variable)
 s.rollno ,s.name, s.percentage -> meaning (str
member (variables)
 p->rollno, p->name, p->percentage -
>meaning(pointer variable)
Using Arrow operator
#include<stdio.h>
#include<string.h>
struct Student
{
int rollno;
char name[25];
float percentage;
};
void main()
{
struct Student *p;
p=(struct Student *)malloc(sizeof(struct Student));
p->rollno = 18;
p->percentage = 93.23;
strcpy(p->name, "sita");
printf("Rollno of Student 1: %dn", p->rollno);
printf("Name of Student 1: %sn",p->name);
 Int a=10;
 Int a[10]={1,2,2,3,4,5,6};
 a=b
Memory Allocation for Structure
 Memory can be allocated for structure variable
not for structure definition
 When we create a structure variable, then
compiler allocate contiguous memory for the
data members of the structure.
 The size of allocated memory is the sum of sizes
of all structure members.
 The data members of structure is accessed with
the help of the structure variable and structure
member name.
struct Student
{
int rollno; 2bytes
char name[25];25 bytes
float percentage; 4bytes
Int mobile;2bytes
};
Struct student s,s1;
Note: Memory can not be created for student.
Memory can be created for structure student variable
s. rollno– 2 bytes, name- 25bytes , percentage – 4
bytes so total memory allocated for s is
31bytes(2+25+4).
Structure Initialization at compile time
 structure variable can also be initialized at compile time.
 Same like avariable (a=4)
struct Student
{
int rollno;
char name[25];
float percentage; int a[10]={1,2,3,3};
};
struct Student s={18,“sita”,93.23};//initialization structure u have to
follow order of definition
 struct Student s;
 s.rollno=18;//initialization of each member separately no need to
follow order.
 s.percentage = 93.23;
 s.name=“sita”;
access structure elements
struct Point
{
int x, y,z;
};
int main()
{
struct Point p1 = {0, 1};
int z;
// Accessing members of point p1
z= p1.x +p1.y;
printf ("x = %d, y = %d", p1.x, p1.y);
Printf(“z=%d”,z);
return 0;
}
Output: x = 0 y=1
Z=1
Initialization:
struct Point
{
int x, y, z;
};
int main()
{
// Examples of initialization using designated initialization
struct Point p1 = {.y = 0, .z = 1, .x = 2};
struct Point p2 = {.x = 20};
printf ("x = %d, y = %d, z = %dn", p1.x, p1.y, p1.z);
printf ("x = %d", p2.x);
return 0;
}
Output: x = 2, y = 0, z = 1
x = 20
structure pointer
we can have pointer to a structure. If we have a pointer to structure,
members are accessed using arrow ( -> ) operator.
#include<stdio.h>
struct Point
{
int x, y;
};
int main()
{
struct Point p1 = {1, 2};
// p2 is a pointer to structure p1
struct Point *p2 = &p1;
// Accessing structure members using structure pointer
printf("%d %d", p2->x, p2->y);
return 0;
}
Output:1 2
Structure Initialization at Run time
//Read and display student details
#include<stdio.h>
#include<string.h>
struct Student
{
int rollno;
char name[25];
float percentage;
};
void main()
{
struct Student s;
printf(“Enter rollno, name and percentagen”);
scanf(“%d”,&s.rollno);
__fpurge(stdin);// The function fpurge() clears the
buffers of the given stream
gets(s.name);
scanf(“%f”,&s.percentage);
printf("Rollno of Student : %dn", s.rollno);
printf("Name of Student : %sn", s.name);
printf("percentage of student : %fn", s.percentage);
}
//Read and display student details using structure pointer
#include<stdio.h>
#include<string.h>
struct Student
{
int rollno;
char name[25];
float percentage;
};
void main()
{
struct Student *p;
p=(struct student *)malloc(sizeof(struct student));
printf(“Enter rollno, name and percentagen”);
scanf(“%d”,&p->rollno);
gets(p->name);
scanf(“%f”,&p->percentage);
printf("Rollno of Student : %dn", p->rollno);
printf("Name of Student : %sn", p->name);
printf("percentage of student : %fn", p->percentage);
}
Read and display employee details
#include<stdio.h>
#include<string.h>
struct employee
{
char name[30];
int empId;
float salary;
};
//next page program
void main()
{
struct employee emp;
printf("nEnter details :n");
printf("Name :");
gets(emp.name);
printf("ID :");
scanf("%d",&emp.empId);
printf("Salary ?:");
scanf("%f",&emp.salary);
printf("nEntered detail is:");
printf("Name: %s" ,emp.name);
printf("Id: %d" ,emp.empId);
printf("Salary: %fn",emp.salary);
}
Limitations of C Structures
 In C language, Structures provide a method
for packing together data of different types.
 A Structure is a helpful tool to handle a group
of logically related data items. However, C
structures have some limitations.
 The C structure does not allow the struct data
type to be treated like built-in data types:
 We cannot use operators like +,- etc. on
Structure variables. For example, consider
the following code:
 No Data Hiding: C Structures do not permit data
hiding. Structure members can be accessed by
any function, anywhere in the scope of the
Structure.
 Functions inside Structure: C structures do not
permit functions inside Structure
 Static Members: C Structures cannot have static
members inside their body
 Access Modifiers: C Programming language do
not support access modifiers. So they cannot be
used in C Structures.
 Construction creation in Structure: Structures
in C cannot have constructor inside Structures
struct number
{
float x;
};
int main()
{
struct number n1,n2,n3;
n1.x=4;
n2.x=3;
n3=n1+n2;
return 0;
}
/*Output:
prog.c: In function 'main':
prog.c:10:7: error:
invalid operands to binary + (have 'struct number' and 'struct number')
n3=n1+n2;
*/
Programs
1. Addition of 2 complex numbers using
structures
2. Multiplication of 2 complex numbers using
structures
3. C Program to Store Information of a Student
Using Structure
4. Program to add two distances in the inch-
feet system
Nested Structures
 One structure variable can be declared inside
other structure as a structure member.
 Nested structure in C is nothing but structure
within structure.
 The structure variables can be a normal
structure variable or a pointer variable to access
the data.
 When a structure contains another structure, it
is called nested structure.
1. Structure within structure in C using normal
variable
2. Structure within structure in C using pointer
Structure within structure in C using normal variable
Examples:
struct Date
{
int day;
int month;
int year;
};
struct student
{
int rollno;
char name[20];
struct Date d;
float percentage;
};
struct student
{
int rollno;
char name[20];
struct Date
{
int day;
int month;
int year;
}d;
float percentage;
};
Structure within structure in C using pointer variable
struct structure1
{
- - - - - - - - - -
- - - - - - - - - -
};
struct structure2
{
- - - - - - - - - -
- - - - - - - - - -
struct structure1 *X;
----------------
};
struct structure2
{
- - - - - - - - - -
- - - - - - - - - -
struct structure1
{
- - - - - - - - - -
- - - - - - - - - -
}*X;
----------------
};
Example:By separate
structure:
struct Date
{
int day;
int month;
int year;
};
struct student
{
int rollno;
char name[20];
struct Date *d;//member
vari
float percentage;
};
Ex:Embedded structure:
struct student
{
int rollno;
char name[20];
struct Date
{
int day;
int month;
int year;
}*d;
float percentage;
};
d is normal variable
s.rollno , s.name, s.d.day, s.d. month,s.d.year,
s.percentagae
d is pointer
s.rollno, s.name, s.d->day, s.d->month, s.d->year,
s.percentage
#include<stdio.h>
#include<string.h>
struct date
{
int day;
int month;
int year;
}d;
struct student_details
{ char name[20];
int id;
struct date d;//member variable of data str
};
int main()
{
struct student_details s;// s is a str variable declaration
printf("enter studendetail namen");
scanf("%s",s.name);
printf("enter idn");
scanf("%d",&s.id);
printf("enter date");
scanf("%d",&s.d.day);//nested
printf("enter monthn");
To read and display student structure details using nested structure as structure
variable
Hint: Use date of birth for nested structure.(
#include<stdio.h>
#include<string.h>
struct Date
{
int day;
int month;
int year;
};
struct student
{
int rollno;
char name[20];
struct Date d;
float percentage;
};
 //next slide program
void main()
{
struct Student s;
printf(“Enter rollno, name and percentagen”);
scanf(“%d”,&s.rollno );
gets(s.name);
scanf(“%f”,&s.percentage);
printf(“Enter Date of birth day,month and yearn”);
scanf(“%d%d%d”,&s.d.day,&s.d.month,&s.d.year);
printf("Rollno of Student : %dn", s.rollno);
printf("Name of Student : %sn", s.name);
printf(“DOB : %d-%d-%d”,s.d.day,s.d.month,s.d.year);
printf("percentage of student : %fn", s.percentage);
}
To read and display student structure details using nested structure as
structure pointer variable
Hint: Use date of birth for nested structure.(By separate structure:)
)
#include<stdio.h>
#include<string.h>
struct Date
{
int day;
int month;
int year;
};
struct student
{
int rollno;
char name[20];
struct Date *d;
float percentage;
};
void main()
{
struct Student s;
printf(“Enter rollno, name and percentagen”);
scanf(“%d”,&s.rollno );
gets(s.name);
scanf(“%f”,&s.percentage);
printf(“Enter Date of birth day,month and yearn”);
scanf(“%d%d%d”,&s.d->day,&s.d->month,&s.d->year);
printf("Rollno of Student : %dn", s.rollno);
printf("Name of Student : %sn", s.name);
printf(“DOB : %d-%d-%d”,s.d->day,s.d->month,s.d->year);
printf("percentage of student : %fn", s.percentage);
}
Nested Structures
 #include<stdio.h>
 struct address
 {
 char city[20];
 int pin;
 char phone[14];
 };
 struct employee
 {
 char name[20];
 struct address add;
 };
 void main ()
 {
 struct employee emp;
 printf("Enter employee information?n");
 scanf("%s %s %d %s",emp.name,emp.add.city, &emp.add.pin, emp.add.phone);
 printf("Printing the employee information....n");
 printf("name: %snCity: %snPincode: %d
nPhone: %s",emp.name,emp.add.city,emp.add.pin,emp.add.phone);
 }
Nested Structures :
 TWO TYPES :
 By separate structure:
 By Embedded structure:.
 1. By separate structure: we create two structures, but the dependent structure
should be used inside the main structure as a member. Consider the following
example.
 struct Date
 {
 int dd;
 int mm;
 int yyyy;
 };
 struct Employee
 {
 int id;
 char name[20];
 struct Date doj;
 }emp1;
above example, doj (date of joining) is the variable of type Date. Here doj is used as a
member in Employee structure. In this way, we can use Date structure in many
structures.
2.Embedded structure:
 The embedded structure enables us to declare the structure
inside the structure. Hence, it requires less line of codes but
it can not be used in multiple data structures. Consider the
following example.
 struct Employee
 {
 int id;
 char name[20];
 struct Date
 {
 int dd;
 int mm;
 int yyyy;
 }doj;
 }emp1;
 An array of structures in C can be defined as the
collection of multiple structures of same where
each variable contains information about
different entities.
 The array of structures in C are used to store
information about multiple entities of different
data types.
 The array of structures is also known as the
collection of structures
Array of structures
detail structure presentation of problem solving
 Index—0 Emp[0].id, emp[0].name,
emp[0].salary
 Index -- 1 Emp[1].id, emp[1].name,
emp[1].salary
 Index --iEmp[i].id, emp[i].name, emp[i].salary

Ex1:array of structures
#include<stdio.h>
#include <string.h>
struct student{
int rollno;
char name[10];
};
int main(){
int i;
struct student st[5];
printf("Enter Records of 5 students");
for(i=0;i<5;i++){
printf("nEnter Rollno:");
scanf("%d",&st[i].rollno);
printf("nEnter Name:");
scanf("%s",&st[i].name);
}
printf("nStudent Information List:");
for(i=0;i<5;i++){
printf("nRollno:%d, Name:%s",st[i].rollno,st[i].name);
}
return 0;
}
// Read and display all employee details in organization
#include<stdio.h>
#include<string.h>
struct employee
{
int id,salary;
char name[20],desg[20];
};
void main()
{
int i,n;
struct employee emp[10];
printf("Enter the no of employeesn");
scanf("%d",&n);
printf("Enter employee details n");
for(i=0;i<n;i++)
{
printf("Enter employee details as id , name , designation , salaryn");
scanf("%d%s%s%d",&emp[i].id, emp[i].name, &emp[i].desg,
&emp[i].salary);
}
printf("Enter employee details aren");
for(i=0;i<n;i++)
{
printf("id:%d,name:%s,designation:%s,salary:%dn",&emp[i].id,
Arrays within structure
 arrays may be the member within structure, this is
known as arrays within structure. Accessing arrays
within structure is similar to accessing other members.
 struct student
 {
 int rollno;
 char name[20];
 intmarks[5]; //array as a member of structure
 float percentage;
 };


 Struct student s;
 s.rollno, s.name, s.percentage

 If s is a variable of type struct student then:

 s.marks[0] – refers to the marks in the first subject
 s.marks[1] – refers to the marks in the second subject
 s.marks[2], s.marks[3], s.marks[4]

 if index I for marks marks[i] --- s.marks[i]

Array within structure
 struct student
 {
 char name[20];
 int rollno;
 int marks[5];
 float percentage;
 };
void main()
{
int i,sum=0;
struct student s;
printf("nEnter Rollno:");
scanf("%d",&s.rollno);
printf("nEnter Name:");
gets(s.name);
printf("nEnter 5 subjects marksn:");
for(i=0;i<5;i++)i=0,1,2,3,4
{
scanf(“%d”,&s.marks[i]);
sum=sum+s.marks[i];
}
s.percentage=(float)sum/5;
printf("n student detailsn");
printf("nRollno:%d, Name:%s",s.rollno,s.name);
printf(“Student Marksn”);
for(i=0;i<5;i++)
{
printf(“%dt”,s.marks[i]);
}
Printf(“percentage=%fn”,s.percentage);
}
Array of Nested structures
 struct Date
 {
 int day;
 int month;
 int year;
 };
 struct student
 {
 int rollno;
 char name[20];
 struct Date d;
 float percentage;
 };
 void main()
 {
 struct Student s[10];
 int i,n;
 printf(“Enter no of studentsn”);
 scanf(“%d”,&n);
 printf(“Enter detailsn”);
 for(i=0;i<n;i++)
 {
 printf(“Enter rollno, name and percentagen”);
 scanf(“%d”,&s[i].rollno );
 gets(s[i].name);
 scanf(“%f”,&s[i].percentage);
 printf(“Enter Date of birth day,month and yearn”);
 scanf(“%d%d%d”,&s[i].d.day,&s[i].d.month,&s[i].d.year);
 }
 for(i=0;i<n;i++)
 {
 printf("Rollno of Student : %dn", s[i].rollno);
 printf("Name of Student : %sn", s[i].name);
 printf(“DOB : %d-%d-%d”,s[i].d.day,s[i].d.month,s[i].d.year);
 printf("percentage of student : %fn", s[i].percentage);
 }
 }
Self-Referential structures
 Self- Referential structures are those structures that have one or more pointers which
point to the same type of structure, as their member.
 Note: Structure member may be pointer variable of same structure but not Normal
variable.
 Ex1:

 struct node
 {
 int data;
 struct node*next;
 };
 node is self-referential structure
 Ex2:
 struct student
 {
 int rollno;
 char name[20];
 float percentage;
 struct student *p;
 };
 Student is self-referential structure
Structures and Functions

More Related Content

Similar to detail structure presentation of problem solving (20)

PDF
PROBLEM SOLVING USING C PPSC- UNIT -5.pdf
JNTUK KAKINADA
 
PDF
Module 5 - Pointer,Structures and Union.pptm.pdf
SudipDebnath20
 
PPTX
Structure in C
Kamal Acharya
 
PDF
1. structure
hasan Mohammad
 
PPTX
Address, Pointers, Arrays, and Structures2.pptx
Dr. Amna Mohamed
 
PDF
Lk module4 structures
Krishna Nanda
 
PPT
Unit4 (2)
mrecedu
 
PPTX
Unit 9. Structure and Unions
Ashim Lamichhane
 
PPTX
Structure.pptx Structure.pptxStructure.pptxStructure.pptxStructure.pptxStruct...
monimhossain14
 
PDF
Structure In C
yndaravind
 
DOCX
C programming structures &amp; union
Bathshebaparimala
 
PPTX
Structure & union
lalithambiga kamaraj
 
PDF
VIT351 Software Development VI Unit4
YOGESH SINGH
 
PPTX
Structure&amp;union
PralhadKhanal1
 
PPTX
Structures and Unions
Vijayananda Ratnam Ch
 
PDF
637225564198396290.pdf
SureshKalirawna
 
PPTX
Structure in C language
CGC Technical campus,Mohali
 
PDF
03 structures
Rajan Gautam
 
PPTX
Chapter 2 part II array and structure.pptx
abenezertekalign118
 
PPTX
STRUCTURES IN C PROGRAMMING
Gurwinderkaur45
 
PROBLEM SOLVING USING C PPSC- UNIT -5.pdf
JNTUK KAKINADA
 
Module 5 - Pointer,Structures and Union.pptm.pdf
SudipDebnath20
 
Structure in C
Kamal Acharya
 
1. structure
hasan Mohammad
 
Address, Pointers, Arrays, and Structures2.pptx
Dr. Amna Mohamed
 
Lk module4 structures
Krishna Nanda
 
Unit4 (2)
mrecedu
 
Unit 9. Structure and Unions
Ashim Lamichhane
 
Structure.pptx Structure.pptxStructure.pptxStructure.pptxStructure.pptxStruct...
monimhossain14
 
Structure In C
yndaravind
 
C programming structures &amp; union
Bathshebaparimala
 
Structure & union
lalithambiga kamaraj
 
VIT351 Software Development VI Unit4
YOGESH SINGH
 
Structure&amp;union
PralhadKhanal1
 
Structures and Unions
Vijayananda Ratnam Ch
 
637225564198396290.pdf
SureshKalirawna
 
Structure in C language
CGC Technical campus,Mohali
 
03 structures
Rajan Gautam
 
Chapter 2 part II array and structure.pptx
abenezertekalign118
 
STRUCTURES IN C PROGRAMMING
Gurwinderkaur45
 

Recently uploaded (20)

PDF
PORTFOLIO Golam Kibria Khan — architect with a passion for thoughtful design...
MasumKhan59
 
PPTX
原版一样(Acadia毕业证书)加拿大阿卡迪亚大学毕业证办理方法
Taqyea
 
DOCX
CS-802 (A) BDH Lab manual IPS Academy Indore
thegodhimself05
 
PDF
MAD Unit - 1 Introduction of Android IT Department
JappanMavani
 
PPTX
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
PPTX
Thermal runway and thermal stability.pptx
godow93766
 
PDF
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
PPTX
Day2 B2 Best.pptx
helenjenefa1
 
PPTX
Element 11. ELECTRICITY safety and hazards
merrandomohandas
 
PDF
Ethics and Trustworthy AI in Healthcare – Governing Sensitive Data, Profiling...
AlqualsaDIResearchGr
 
PDF
Set Relation Function Practice session 24.05.2025.pdf
DrStephenStrange4
 
PPTX
Worm gear strength and wear calculation as per standard VB Bhandari Databook.
shahveer210504
 
PDF
MAD Unit - 2 Activity and Fragment Management in Android (Diploma IT)
JappanMavani
 
PPTX
Arduino Based Gas Leakage Detector Project
CircuitDigest
 
PDF
GTU Civil Engineering All Semester Syllabus.pdf
Vimal Bhojani
 
PPTX
265587293-NFPA 101 Life safety code-PPT-1.pptx
chandermwason
 
PPTX
GitOps_Without_K8s_Training_detailed git repository
DanialHabibi2
 
PPTX
Green Building & Energy Conservation ppt
Sagar Sarangi
 
PPTX
MobileComputingMANET2023 MobileComputingMANET2023.pptx
masterfake98765
 
PPTX
artificial intelligence applications in Geomatics
NawrasShatnawi1
 
PORTFOLIO Golam Kibria Khan — architect with a passion for thoughtful design...
MasumKhan59
 
原版一样(Acadia毕业证书)加拿大阿卡迪亚大学毕业证办理方法
Taqyea
 
CS-802 (A) BDH Lab manual IPS Academy Indore
thegodhimself05
 
MAD Unit - 1 Introduction of Android IT Department
JappanMavani
 
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
Thermal runway and thermal stability.pptx
godow93766
 
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
Day2 B2 Best.pptx
helenjenefa1
 
Element 11. ELECTRICITY safety and hazards
merrandomohandas
 
Ethics and Trustworthy AI in Healthcare – Governing Sensitive Data, Profiling...
AlqualsaDIResearchGr
 
Set Relation Function Practice session 24.05.2025.pdf
DrStephenStrange4
 
Worm gear strength and wear calculation as per standard VB Bhandari Databook.
shahveer210504
 
MAD Unit - 2 Activity and Fragment Management in Android (Diploma IT)
JappanMavani
 
Arduino Based Gas Leakage Detector Project
CircuitDigest
 
GTU Civil Engineering All Semester Syllabus.pdf
Vimal Bhojani
 
265587293-NFPA 101 Life safety code-PPT-1.pptx
chandermwason
 
GitOps_Without_K8s_Training_detailed git repository
DanialHabibi2
 
Green Building & Energy Conservation ppt
Sagar Sarangi
 
MobileComputingMANET2023 MobileComputingMANET2023.pptx
masterfake98765
 
artificial intelligence applications in Geomatics
NawrasShatnawi1
 
Ad

detail structure presentation of problem solving

  • 2. Unit-II(Structures)  Introduction to Structures  Definition  Initialization of Structures  Accessing structure members  Nested Structures  Array of Structures  Structures and Functions  Unions  Typedef  Enumerated Data types.
  • 3. Introduction to Structures:  Definition :Structure is a collection of heterogeneous data elements.  Structure is a user-defined datatype in C language which allows us to combine data of different data types.  structures we can combine various data types to store a specific type of data.  Structures are used to represent a record  Structure helps to construct a complex data type which is more meaningful.
  • 4. Example 1:  I want to keep track of your books in a library. You might want to track the following attributes about each book −  Title  Author  Subject  cast
  • 5. Example 2:  If I want to write a program to store Student information. Student's name age branch permanent address father's name ….etc  which included different data types( string values, integer values etc).  In structure, data is stored in form of records.
  • 6. Defining a Structure  To define a structure, you must use the struct statement.  The struct statement defines a new data type, with more than one member.  Syntax: struct structure_name(or)structure tag { //member variable 1 ; //member variable 2; //member variable 3; ... };
  • 7. Defining a Structure Syntax: struct structure tag(or)structure name { member definition; member definition; ... member definition; } [one or more structure variables];  The structure tag is optional . Each member definition is a normal variable definition, (int i; or float f; or any other valid variable definition.)
  • 8. EX: Struct student_detail { char studentname[20]; int age; int rollno; float intermarks; char address[20]; };
  • 9.  we start with the struct keyword.  we have to mention all the member variables, which are nothing but normal C language variables of different types like int, float, array etc.  Note: The closing curly brace in the structure type declaration must be followed by a semicolon(;).
  • 10. Example of Structure struct student_name { char studentname[20]; int age; char branch[20] ; char gender[10]; }; Here,  struct Student name declares a structure to hold the details of a studentdetails .  which consists of 4 data fields, namely name, age, branch and gender.  These fields are called structure elements or members of structures.
  • 11. Example of Structure: struct Books { char title[50]; char author[50]; char subject[100]; int book_id; } book; book is the name of the structure and is called as the structure tag.
  • 12.  Note: Structure members cannot be initialized during structure definition time.  Structure name is new data type name…not a variable  int a=10
  • 13. Declaring Structure Variables  It is possible to declare variables of a structure, either along with structure definition or after the structure is defined.  Structure variable declaration is similar to the declaration of any normal variable of any other datatype.  Structure variables can be declared in following two ways: 1. Declaring Structure variables separately 2. Declaring Structure variables along with structure definition
  • 14. Declaring Structure variables separately:  Syntax: struct structurename var1,var2…; struct Student { int rollno; char name[25]; float percentage; }; struct Student s1, s2; //declaring variables of struct Student the above statement can be used in any function in a program //s1 , s2 will local variables in the function
  • 15. Declaring Structure variables with structure definition struct Student { int rollno; char name[25]; float percentage; }s1,s2; //s1 and s2 are global variables Here ,S1 and S2 are variables of structure Student. However this approach is not much recommended.
  • 16. Access members of a structure  There are two types of operators used for accessing members of a structure. 1. (.) Member operator(dot operator) 2. (-> ) Structure pointer operator(arrow operator) Ex:  you want to access the salary of person2. Here's how you can do it. person2.salary
  • 17. Access members of a structure  (.) Member operator(dot operator):  This operator can be used to access structure members with structure variables..  Syntax: structurevariable. structuremember; struct student s; Ex: s.rollno; s.name; s.percentage;
  • 18. dot operator(program) #include<stdio.h> #include<string.h> struct Student { int rollno; char name[25]; float percentage; }; void main() { struct Student s; s.rollno= 18; s.percentage = 93.23; strcpy(s.name, "sita"); printf("Rollno of Student 1: %dn", s.rollno); printf("Name of Student 1: %sn", s.name); printf("percentage of student 1: %fn", s.percentage); }
  • 19. #include <stdio.h> #include <string.h> struct Books { char title[50]; char author[50]; char subject[100]; int book_id; }; int main( ) { struct Books Book1; /* Declare Book1 of type Book */ /* book 1 specification */ strcpy( Book1.title, "C Programming"); strcpy( Book1.author, "Nuha Ali"); strcpy( Book1.subject, "C Programming Tutorial"); Book1.book_id = 6495407; /* print Book1 info */ printf( "Book 1 title : %sn", Book1.title); printf( "Book 1 author : %sn", Book1.author); printf( "Book 1 subject : %sn", Book1.subject); printf( "Book 1 book_id : %dn", Book1.book_id); return 0; }
  • 20. Structure pointer operator(->arrow operator)  This operator can be used to access structure members with structure pointer variables.  Syntax: structure pointervariable- >structuremember;  struct student *p; //memory should create for pointer variables using malloc  p=(struct student *)malloc(sizeof(struct student));
  • 21.  Ex: p->rollno, p->name, p->percentage  s.rollno,s.name,s.perc  Structure members can be accessed and assigned values in a number of ways.  Structure members have no meaning individually without the structure variables.  Rollno,name,percentage --- no meaning(normal variable)  s.rollno ,s.name, s.percentage -> meaning (str member (variables)  p->rollno, p->name, p->percentage - >meaning(pointer variable)
  • 22. Using Arrow operator #include<stdio.h> #include<string.h> struct Student { int rollno; char name[25]; float percentage; }; void main() { struct Student *p; p=(struct Student *)malloc(sizeof(struct Student)); p->rollno = 18; p->percentage = 93.23; strcpy(p->name, "sita"); printf("Rollno of Student 1: %dn", p->rollno); printf("Name of Student 1: %sn",p->name);
  • 23.  Int a=10;  Int a[10]={1,2,2,3,4,5,6};  a=b
  • 24. Memory Allocation for Structure  Memory can be allocated for structure variable not for structure definition  When we create a structure variable, then compiler allocate contiguous memory for the data members of the structure.  The size of allocated memory is the sum of sizes of all structure members.  The data members of structure is accessed with the help of the structure variable and structure member name.
  • 25. struct Student { int rollno; 2bytes char name[25];25 bytes float percentage; 4bytes Int mobile;2bytes }; Struct student s,s1; Note: Memory can not be created for student. Memory can be created for structure student variable s. rollno– 2 bytes, name- 25bytes , percentage – 4 bytes so total memory allocated for s is 31bytes(2+25+4).
  • 26. Structure Initialization at compile time  structure variable can also be initialized at compile time.  Same like avariable (a=4) struct Student { int rollno; char name[25]; float percentage; int a[10]={1,2,3,3}; }; struct Student s={18,“sita”,93.23};//initialization structure u have to follow order of definition  struct Student s;  s.rollno=18;//initialization of each member separately no need to follow order.  s.percentage = 93.23;  s.name=“sita”;
  • 27. access structure elements struct Point { int x, y,z; }; int main() { struct Point p1 = {0, 1}; int z; // Accessing members of point p1 z= p1.x +p1.y; printf ("x = %d, y = %d", p1.x, p1.y); Printf(“z=%d”,z); return 0; } Output: x = 0 y=1 Z=1
  • 28. Initialization: struct Point { int x, y, z; }; int main() { // Examples of initialization using designated initialization struct Point p1 = {.y = 0, .z = 1, .x = 2}; struct Point p2 = {.x = 20}; printf ("x = %d, y = %d, z = %dn", p1.x, p1.y, p1.z); printf ("x = %d", p2.x); return 0; } Output: x = 2, y = 0, z = 1 x = 20
  • 29. structure pointer we can have pointer to a structure. If we have a pointer to structure, members are accessed using arrow ( -> ) operator. #include<stdio.h> struct Point { int x, y; }; int main() { struct Point p1 = {1, 2}; // p2 is a pointer to structure p1 struct Point *p2 = &p1; // Accessing structure members using structure pointer printf("%d %d", p2->x, p2->y); return 0; } Output:1 2
  • 30. Structure Initialization at Run time //Read and display student details #include<stdio.h> #include<string.h> struct Student { int rollno; char name[25]; float percentage; };
  • 31. void main() { struct Student s; printf(“Enter rollno, name and percentagen”); scanf(“%d”,&s.rollno); __fpurge(stdin);// The function fpurge() clears the buffers of the given stream gets(s.name); scanf(“%f”,&s.percentage); printf("Rollno of Student : %dn", s.rollno); printf("Name of Student : %sn", s.name); printf("percentage of student : %fn", s.percentage); }
  • 32. //Read and display student details using structure pointer #include<stdio.h> #include<string.h> struct Student { int rollno; char name[25]; float percentage; }; void main() { struct Student *p; p=(struct student *)malloc(sizeof(struct student)); printf(“Enter rollno, name and percentagen”); scanf(“%d”,&p->rollno); gets(p->name); scanf(“%f”,&p->percentage); printf("Rollno of Student : %dn", p->rollno); printf("Name of Student : %sn", p->name); printf("percentage of student : %fn", p->percentage); }
  • 33. Read and display employee details #include<stdio.h> #include<string.h> struct employee { char name[30]; int empId; float salary; }; //next page program
  • 34. void main() { struct employee emp; printf("nEnter details :n"); printf("Name :"); gets(emp.name); printf("ID :"); scanf("%d",&emp.empId); printf("Salary ?:"); scanf("%f",&emp.salary); printf("nEntered detail is:"); printf("Name: %s" ,emp.name); printf("Id: %d" ,emp.empId); printf("Salary: %fn",emp.salary); }
  • 35. Limitations of C Structures  In C language, Structures provide a method for packing together data of different types.  A Structure is a helpful tool to handle a group of logically related data items. However, C structures have some limitations.  The C structure does not allow the struct data type to be treated like built-in data types:  We cannot use operators like +,- etc. on Structure variables. For example, consider the following code:
  • 36.  No Data Hiding: C Structures do not permit data hiding. Structure members can be accessed by any function, anywhere in the scope of the Structure.  Functions inside Structure: C structures do not permit functions inside Structure  Static Members: C Structures cannot have static members inside their body  Access Modifiers: C Programming language do not support access modifiers. So they cannot be used in C Structures.  Construction creation in Structure: Structures in C cannot have constructor inside Structures
  • 37. struct number { float x; }; int main() { struct number n1,n2,n3; n1.x=4; n2.x=3; n3=n1+n2; return 0; } /*Output: prog.c: In function 'main': prog.c:10:7: error: invalid operands to binary + (have 'struct number' and 'struct number') n3=n1+n2; */
  • 38. Programs 1. Addition of 2 complex numbers using structures 2. Multiplication of 2 complex numbers using structures 3. C Program to Store Information of a Student Using Structure 4. Program to add two distances in the inch- feet system
  • 39. Nested Structures  One structure variable can be declared inside other structure as a structure member.  Nested structure in C is nothing but structure within structure.  The structure variables can be a normal structure variable or a pointer variable to access the data.  When a structure contains another structure, it is called nested structure. 1. Structure within structure in C using normal variable 2. Structure within structure in C using pointer
  • 40. Structure within structure in C using normal variable
  • 41. Examples: struct Date { int day; int month; int year; }; struct student { int rollno; char name[20]; struct Date d; float percentage; }; struct student { int rollno; char name[20]; struct Date { int day; int month; int year; }d; float percentage; };
  • 42. Structure within structure in C using pointer variable struct structure1 { - - - - - - - - - - - - - - - - - - - - }; struct structure2 { - - - - - - - - - - - - - - - - - - - - struct structure1 *X; ---------------- }; struct structure2 { - - - - - - - - - - - - - - - - - - - - struct structure1 { - - - - - - - - - - - - - - - - - - - - }*X; ---------------- };
  • 43. Example:By separate structure: struct Date { int day; int month; int year; }; struct student { int rollno; char name[20]; struct Date *d;//member vari float percentage; }; Ex:Embedded structure: struct student { int rollno; char name[20]; struct Date { int day; int month; int year; }*d; float percentage; };
  • 44. d is normal variable s.rollno , s.name, s.d.day, s.d. month,s.d.year, s.percentagae d is pointer s.rollno, s.name, s.d->day, s.d->month, s.d->year, s.percentage
  • 45. #include<stdio.h> #include<string.h> struct date { int day; int month; int year; }d; struct student_details { char name[20]; int id; struct date d;//member variable of data str }; int main() { struct student_details s;// s is a str variable declaration printf("enter studendetail namen"); scanf("%s",s.name); printf("enter idn"); scanf("%d",&s.id); printf("enter date"); scanf("%d",&s.d.day);//nested printf("enter monthn");
  • 46. To read and display student structure details using nested structure as structure variable Hint: Use date of birth for nested structure.( #include<stdio.h> #include<string.h> struct Date { int day; int month; int year; }; struct student { int rollno; char name[20]; struct Date d; float percentage; };  //next slide program
  • 47. void main() { struct Student s; printf(“Enter rollno, name and percentagen”); scanf(“%d”,&s.rollno ); gets(s.name); scanf(“%f”,&s.percentage); printf(“Enter Date of birth day,month and yearn”); scanf(“%d%d%d”,&s.d.day,&s.d.month,&s.d.year); printf("Rollno of Student : %dn", s.rollno); printf("Name of Student : %sn", s.name); printf(“DOB : %d-%d-%d”,s.d.day,s.d.month,s.d.year); printf("percentage of student : %fn", s.percentage); }
  • 48. To read and display student structure details using nested structure as structure pointer variable Hint: Use date of birth for nested structure.(By separate structure:) ) #include<stdio.h> #include<string.h> struct Date { int day; int month; int year; }; struct student { int rollno; char name[20]; struct Date *d; float percentage; };
  • 49. void main() { struct Student s; printf(“Enter rollno, name and percentagen”); scanf(“%d”,&s.rollno ); gets(s.name); scanf(“%f”,&s.percentage); printf(“Enter Date of birth day,month and yearn”); scanf(“%d%d%d”,&s.d->day,&s.d->month,&s.d->year); printf("Rollno of Student : %dn", s.rollno); printf("Name of Student : %sn", s.name); printf(“DOB : %d-%d-%d”,s.d->day,s.d->month,s.d->year); printf("percentage of student : %fn", s.percentage); }
  • 50. Nested Structures  #include<stdio.h>  struct address  {  char city[20];  int pin;  char phone[14];  };  struct employee  {  char name[20];  struct address add;  };  void main ()  {  struct employee emp;  printf("Enter employee information?n");  scanf("%s %s %d %s",emp.name,emp.add.city, &emp.add.pin, emp.add.phone);  printf("Printing the employee information....n");  printf("name: %snCity: %snPincode: %d nPhone: %s",emp.name,emp.add.city,emp.add.pin,emp.add.phone);  }
  • 51. Nested Structures :  TWO TYPES :  By separate structure:  By Embedded structure:.  1. By separate structure: we create two structures, but the dependent structure should be used inside the main structure as a member. Consider the following example.  struct Date  {  int dd;  int mm;  int yyyy;  };  struct Employee  {  int id;  char name[20];  struct Date doj;  }emp1; above example, doj (date of joining) is the variable of type Date. Here doj is used as a member in Employee structure. In this way, we can use Date structure in many structures.
  • 52. 2.Embedded structure:  The embedded structure enables us to declare the structure inside the structure. Hence, it requires less line of codes but it can not be used in multiple data structures. Consider the following example.  struct Employee  {  int id;  char name[20];  struct Date  {  int dd;  int mm;  int yyyy;  }doj;  }emp1;
  • 53.  An array of structures in C can be defined as the collection of multiple structures of same where each variable contains information about different entities.  The array of structures in C are used to store information about multiple entities of different data types.  The array of structures is also known as the collection of structures Array of structures
  • 55.  Index—0 Emp[0].id, emp[0].name, emp[0].salary  Index -- 1 Emp[1].id, emp[1].name, emp[1].salary  Index --iEmp[i].id, emp[i].name, emp[i].salary 
  • 56. Ex1:array of structures #include<stdio.h> #include <string.h> struct student{ int rollno; char name[10]; }; int main(){ int i; struct student st[5]; printf("Enter Records of 5 students"); for(i=0;i<5;i++){ printf("nEnter Rollno:"); scanf("%d",&st[i].rollno); printf("nEnter Name:"); scanf("%s",&st[i].name); } printf("nStudent Information List:"); for(i=0;i<5;i++){ printf("nRollno:%d, Name:%s",st[i].rollno,st[i].name); } return 0; }
  • 57. // Read and display all employee details in organization #include<stdio.h> #include<string.h> struct employee { int id,salary; char name[20],desg[20]; }; void main() { int i,n; struct employee emp[10]; printf("Enter the no of employeesn"); scanf("%d",&n); printf("Enter employee details n"); for(i=0;i<n;i++) { printf("Enter employee details as id , name , designation , salaryn"); scanf("%d%s%s%d",&emp[i].id, emp[i].name, &emp[i].desg, &emp[i].salary); } printf("Enter employee details aren"); for(i=0;i<n;i++) { printf("id:%d,name:%s,designation:%s,salary:%dn",&emp[i].id,
  • 58. Arrays within structure  arrays may be the member within structure, this is known as arrays within structure. Accessing arrays within structure is similar to accessing other members.  struct student  {  int rollno;  char name[20];  intmarks[5]; //array as a member of structure  float percentage;  }; 
  • 59.   Struct student s;  s.rollno, s.name, s.percentage   If s is a variable of type struct student then:   s.marks[0] – refers to the marks in the first subject  s.marks[1] – refers to the marks in the second subject  s.marks[2], s.marks[3], s.marks[4]   if index I for marks marks[i] --- s.marks[i] 
  • 60. Array within structure  struct student  {  char name[20];  int rollno;  int marks[5];  float percentage;  };
  • 61. void main() { int i,sum=0; struct student s; printf("nEnter Rollno:"); scanf("%d",&s.rollno); printf("nEnter Name:"); gets(s.name); printf("nEnter 5 subjects marksn:"); for(i=0;i<5;i++)i=0,1,2,3,4 { scanf(“%d”,&s.marks[i]); sum=sum+s.marks[i]; } s.percentage=(float)sum/5; printf("n student detailsn"); printf("nRollno:%d, Name:%s",s.rollno,s.name); printf(“Student Marksn”); for(i=0;i<5;i++) { printf(“%dt”,s.marks[i]); } Printf(“percentage=%fn”,s.percentage); }
  • 62. Array of Nested structures  struct Date  {  int day;  int month;  int year;  };  struct student  {  int rollno;  char name[20];  struct Date d;  float percentage;  };
  • 63.  void main()  {  struct Student s[10];  int i,n;  printf(“Enter no of studentsn”);  scanf(“%d”,&n);  printf(“Enter detailsn”);  for(i=0;i<n;i++)  {  printf(“Enter rollno, name and percentagen”);  scanf(“%d”,&s[i].rollno );  gets(s[i].name);  scanf(“%f”,&s[i].percentage);  printf(“Enter Date of birth day,month and yearn”);  scanf(“%d%d%d”,&s[i].d.day,&s[i].d.month,&s[i].d.year);  }  for(i=0;i<n;i++)  {  printf("Rollno of Student : %dn", s[i].rollno);  printf("Name of Student : %sn", s[i].name);  printf(“DOB : %d-%d-%d”,s[i].d.day,s[i].d.month,s[i].d.year);  printf("percentage of student : %fn", s[i].percentage);  }  }
  • 64. Self-Referential structures  Self- Referential structures are those structures that have one or more pointers which point to the same type of structure, as their member.  Note: Structure member may be pointer variable of same structure but not Normal variable.  Ex1:   struct node  {  int data;  struct node*next;  };  node is self-referential structure  Ex2:  struct student  {  int rollno;  char name[20];  float percentage;  struct student *p;  };  Student is self-referential structure