L31 Structures
L31 Structures
Objectives
To learn and appreciate the following concepts
▪We’ve seen variables of simple data types, such as float, char, and int.
➢We saw derived data type, arrays to store group of related data.
▪But, these basic types does not support the storage of compound data.
✓Structures
▪Definition:
▪collection of one or more variables, possibly of different types, grouped
together under a single name for convenient handling
• Examples:
❑Student record: student id, name, branch, gender, start year, …
❑Bank account: account number, name, address, balance, …
❑Address book: name, address, telephone number, …
struct structure_name
{
data_type member1;
data_type member2;
…
};
struct Date
{
Members of the
int day; structure Date
int month;
int year;
};
Name Name
Student1 Id Gender Id Gender Student2
Dept Dept
struct student
{
int rollno;
int age;
char name[10];
float height;
}s1, s2, s3; /* Defines 3 variables of type student */
Assigning string:
strcpy(s1.name, “Rama”); struct student
{
Assignment statement: int rollno;
s1.rollno = 1335; int age;
char name[20];
s1.age = 18; float height;
s1.height = 5.8; }s1;
main()
{
struct
{
int rollno;
int age;
}s1 ={20, 21};
…
}
6/4/2022 CSE 1051 Department of CSE 18
Structure Initialization Methods
main ( )
{
struct Student
{
int rollno;
int age;
};
Student s1={20, 21};
Student s2={21, 21};
}
struct Student
{
int rollno;
int age;
} s1={20, 21};
main ( )
{
Student s2={21, 21};
…
…
}
6/4/2022 CSE 1051 Department of CSE 20
Structure: Example
struct Book { // definition
char title[20];
char author[15];
int main( ){ int pages;
struct Book b1; float price;
//Input };
printf(“Input values”);
scanf(“%s %s %d %f”, b1.title, b1.author, &b1.pages, &b1.price);
//gets(b1.title); gets(b1.author);
//output
printf(“%s %s %d %f”, b1.title, b1.author, b1.pages, b1.price);
return 0;
}
6/4/2022 CSE 1051 Department of CSE 21
Summary
• Structure Basics