Structure-Basic Concepts, Array within structure, Array of structure
Size: 195.52 KB
Language: en
Added: Nov 28, 2024
Slides: 11 pages
Slide Content
Structures in C
Dr. Mary Jacob
Asst.Professor, Department of Computer Science
Kristu Jayanti College,Autonomous
Bengaluru
What is a Structure?
www.kristujayanti.edu.in
A structure is a user-defined data type in C that groups related variables of
different data types under a single name.
- Each variable in the structure is called a member or field.
Purpose of Structures
vOrganize related data:
Helps in grouping different types of data together, such as details of a
student (name, roll number, marks)
vCode clarity and efficiency:
Avoids multiple variables for different attributes of the same entity.
Use Cases of Structures
www.kristujayanti.edu.in
vStudent Record: Structure to store student details such as roll
number, name, and marks.
vEmployee Record: Structure to store employee information such as
ID, name, department, salary, etc.
vDate Structure: Structure to represent date with members for day,
month, and year.
Defining a Structure?
www.kristujayanti.edu.in
Syntax:
struct StructureName
{
dataType member1;
dataType member2;
...
};
Example:
struct Student
{
int roll_no;
char name[50];
float marks;
};
Østruct keyword is used to define a structure.
ØStructureName is the name of the structure.
Array within a Structure
www.kristujayanti.edu.in
A structure can contain arrays as its members, which allows for grouping
multiple values of the same type.
Accessing Structure Members
www.kristujayanti.edu.in
Dot Operator (.) - Used to access structure members.
Example:
printf("%d", s1.roll_no); // Accessing roll_no of student s1
printf("%s", s1.name); // Accessing name of student s1
printf("%.f", s1.marks); // Accessing marks of student s1
Array of Structures
www.kristujayanti.edu.in
An array of structures is an array where each element is a structure.This allows
you to store multiple records of a structure type in an array.
Syntax:
struct StructureName
{
dataType member1;
dataType member2;
...
};
struct StructureName arrayName[size];
Example:
struct Student
{
int roll_no;
char name[50];
float marks;
};
struct Student students[3]; // Array of structures
Summary
www.kristujayanti.edu.in
üA structure in C allows grouping multiple data types into one
unit.
üStructures are useful for representing real-world entities and
organizing complex data.
üThe key operations with structures include declaration,
initialization, accessing members, and using pointers.
üStructures can be nested or used in arrays.