Download as pdf or txt
Download as pdf or txt
You are on page 1of 31

CSE287

Computer Programming

Lecture 8:
Structures in C

Khaled Mahmud Shahriar


Assistant Professor
Department of CSE, BUET
Structure
• Aggregate data type
• Composed of two or more related variables
• Called member
• Each member can be of different type
• Structure allows us to -
• keep logically related data together as a unit
• return more than one values from a function
Structure Declaration
General Form Example-1 Example-2 Example-3
struct tag-name { struct point { struct { struct point{
int x; int x; int x;
type member1;
int y; int y; int y;
type member2; } p1, p2; } p1,p2; }
type member3; struct point p1, p2;
.
.
• Structure declaration without any variable name does not reserve any
. storage
type memberN; • Describes template or shape of a structure
} variable-list;

• The keyword struct means that a structure type is defined


• tag-name is the name of the type
• Either tag-name or variable-list is optional
Structure Declaration
• Structure can be declared
• Locally (inside a function)
• Globally (outside of any function)

• Structure declaration and structure variable declaration are different.


• Variables can be declared during structure declaration or later

• It is possible to declare structure globally and declare the variables of


the structure locally
Structure Declaration
void func(); int main()
///Structure can be declared without declaring {
any variable of it struct student3 {
struct student1 char name[40];
{ int id;
char name[40]; double cgpa;
int id; };
double cgpa; struct student4 {
}; char name[40];
///Variables can be declared during the int id;
declaration of structure double cgpa;
struct student2 }s41, s42;
{ struct student1 s11 , s12;
char name[40]; struct student2 s23 , s24;
int id; struct student3 s31 , s32;
double cgpa; struct student4 s43 , s44;
}s21, s22; func();
return 0;
}

void func()
{
struct student1 s13 ;
struct student2 s25 ;
///struct student3 s33; //error when uncommented
… … …
}
Structure Initialization
struct point {
int x;
int y;
};
Initialization
int main()
{
struct point p1={5, 2};//ok
struct point p2;
p2={10, 5};//error, not possible
return 0;
}

Not allowed
Accessing Structure Member
• Use dot operator to access the member of a structure
StructureVariable.member
• For example, if p1 is a structure variable, use
printf("%d, %d\n", p1.x, p1.y);
• For scanf or other cases where address of a member is required, use
& operator before structure variable name not before member name.
&StructureVariable.member
• For example, if p1 is a structure variable,
scanf("%d %d\n", &p1.x, &p1.y);
Structure Example
#include <stdio.h>
#include <string.h>

struct point {
int x;
int y;
char name[80];
};

int main()
{
struct point p1 = {5, 5, "A"};
struct point p2,p3;
p2.x = 10;
p2.y = 15;
strcpy(p2.name, "B");
scanf("%d %d %s",&p3.x,&p3.y,p3.name);//input: 10 20 C

printf("%d %d %s\n", p1.x, p1.y, p1.name);


printf("%d %d %s\n", p2.x, p2.y, p2.name);
printf("%d %d %s\n", p3.x, p3.y, p3.name);
return 0;
}
Structure as a Data Type
• Structures can be considered like other data types
• Thus, we can -
• use the sizeof operator with structures to determine size,
• assign one structure variable to another,
• create arrays of structures,
• pass structure(s) to a function and return a structure from a function,
• make a structure member of another structure, i.e., nesting structures,
• take pointer/references of structures,
• allocate and free structure
Structure Size
#include <stdio.h>
#include <string.h>

struct point {
int x;
int y;
char name[30];
};

int main()
{
struct point p1;
printf("Size of structure point: %d byte.",sizeof(struct point));
return 0;
}
Structure Size
• The size of a structure element is greater than or equal to the
summation of sizes of its fields (members).
• Why may it be greater?
• For the ease of memory access! Memory is not access bytewise rather
accessed 4 bytes per operation or 8 bytes per operation. So, it is common to
find the size of the structure as the multiple 4 or 8.
• Memory access is higher topic, not for now. Just remember the reason larger
structure size.
• Check the link below for details:
https://www.geeksforgeeks.org/is-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member/
Structure Assignment
#include <stdio.h>
#include <string.h>

struct point {
int x;
int y;
};

int main()
{
struct point p1,p2;
p1.x=10;
p1.y=20;
p2=p1;
printf("The point p2 is (%d,%d)",p2.x,p2.y);
return 0;
}
Structure Assignment
struct point {
int x;
int y;
int z;
};
struct vector {
int x;
int y;
int z;
};

int main()
{
struct point p;
struct vector v;
v=p; Structure type must be the
return 0; same for assignment
}
Structure Array
• A structure array can be declared like the process of a normal variable
declaration.
• Index must be used to access an element of the array
• To access the member of that element, use dot operator after the index
Structure Array
• The member of a structure and a normal variable in a function can
have the same name.

Member x and int x are different


Structure in Function
• A structure object can be passed into a function and a structure object can
be returned from a function.
• The function prototype can be written above the structure definition but
the full definition of the function must be written below the definition.
Structure in Function
struct point {
float x;
float y;
};

struct point midPoint(struct point point1, struct point point2);

int main(void)
{
struct point P, Q, M;
scanf("%f %f",&P.x,&P.y);
scanf("%f %f",&Q.x,&Q.y);
M= midPoint(P,Q);
printf("%f %f",M.x,M.y);
return 0;
}

struct point midPoint(struct point point1, struct point point2)


{
struct point result;
result.x = (point1.x+point2.x)/2;
result.y = (point1.y+point2.y)/2;
return result;
};
Nested Structure
• A structure can be used inside another structure and so on.
• If structure A is used inside structure B, then structure A must be
declared before structure B.
• If structure A is used inside structure B, then B is the outer structure and
A is inner structure.
• During accessing the elements of nested structure object, use the
outermost structure variable first, then a dot, then the inner one, and so
on.
Nested Structure
struct point { int main()
int x; { p1
int y; struct point p1, p2;
}; p1.x = 10;
p1.y = 15;
struct rect { p2.x = 20; p2
struct point pt1; p2.y = 10;
struct point pt2; struct rect r1;
}; r1.pt1 = p1;
r1.pt2 = p2;
Structure point must be declared //struct rect r1 = {p1, p2};
before the structure rect int x1 = r1.pt1.x;
int y1 = r1.pt1.y;
int x2 = r1.pt2.x;
int y2 = r1.pt2.y;
printf("(%d %d), (%d %d)\n", x1, y1, x2, y2);
return 0;
}
typedef (user defined data types)
• typedef type new-type typedef double Matrix[20][20];

• type: an existing data type int main(void)


{
• Example: Matrix a;
for(int i=0;i<3;i++)
• typedef int age for(int j=0;j<3;j++)
scanf("%d",&a[i][j]);
• age is a user defined data type, printf("Here goes the matrix:\n")
equivalent to int for(int i=0;i<3;i++){
for(int j=0;j<3;j++)
• We can declare variables such as: printf("%d ",a[i][j]);
age a, b,c printf("\n");
}
return 0;
}
typedef with Structure
Syntax-1 Example
typedef struct typedef struct {
{ int month;
type member1; int day;
type member2; int year;
… … … } Date;
} new-type;

Syntax-2 Example
struct tag struct date{
{ int month;
type member1; int day;
type member2; int year;
… … … };
}; typedef struct date Date;
typedef struct tag new-type;
Use of Typedef
typedef struct point {
float x;
float y;
} Point;

Point midPoint(Point point1, Point point2);


int main(void)
{
Point P, Q, M;
scanf("%f %f",&P.x,&P.y);
scanf("%f %f",&Q.x,&Q.y);
M= midPoint(P,Q);
printf("%f %f",M.x,M.y);
return 0;
}

Point midPoint(Point point1, Point point2)


{
Point result;
result.x = (point1.x+point2.x)/2;
result.y = (point1.y+point2.y)/2;
return result;
}
Structure Practice Problem: Courses and Students

Live Demo
Structure Practice Problem: int main(){
Courses and Students int i,n=0,stId,sIndex, choice ;
Student st [60];
while(1){
choice =printMenu();
switch(choice){
case 1:
takeInput (st,n);
n ++; break;
case 2:
printf ("Enter the student id to search:
");
struct course{ scanf ("%d",&stId);
sIndex =searchByStudentID (st,n,stId);
char courseId[100]; if(sIndex>=0) printStudentInfo (st,sIndex);
double gradePoint; else printf("Not found.\n" );
}; break;
typedef struct course Course; case 3:
calculateGPA (st,n); break;
struct student{
case 4:
char name[100]; sortStudentsByGPA (st,n); break;
int id;
case 5:
int numCourses;
printResult (st,n); break;
double gpa;
Course cList[100]; default:
return 0;
}; }
typedef struct student Student; }
}
Structure Practice Problem: Courses and Students (contd.)
struct course{ void printResult (Student st [], int numOfSt){
char courseId[100]; int n;
double gradePoint ; printf ("---Result Sheet---\n" );
}; for(n=0;n<numOfSt;n++){
typedef struct course Course ; printf ("Name: %s, GPA: %lf\n" ,st[n].name,st[n].gpa);
struct student{ }
char name[100]; }
int id; void printStudentInfo (Student st [], int n){
int numCourses ; printf ("Name: %s, Id: %d, GPA: %lf\n" ,st[n].name,
double gpa; st[n].id,
Course cList [100]; st[n].gpa);
}; for(int i=0;i<st[n].numCourses ;i++)
typedef struct student Student ; printf ("Course Name: %s, Grade Point: %lf\n" ,
st[n].cList[i].name,st[n].cList[i].gradePoint );
}
int printMenu (){ void takeInput (Student st [], int n){
int choice; int i;
printf ("---Menu----\n" ); printf ("\nEnter name, id and number of courses of student
printf ("1. Add a student.\n" ); %d: " ,n);
printf ("2. Search by studentId.\n" ); scanf(" %s%d%d",st[n].name,&st[n].id,&st[n].numCourses );
printf ("3. Calculate gpa.\n" ); for(i=0;i<st[n].numCourses ;i++){
printf ("4. Sort students by gpa.\n" ); printf ("Enter name and grade point of course %d for
printf ("5. Print result.\n" ); %s: ",i,st[n].name);
printf ("6. Exit program.\n" ); scanf (" %s%lf",st[n].cList[i].name,
printf ("\tEnter your choice: " ); &st[n].cList[i].gradePoint );
scanf("%d",&choice); }
return choice; }
}
Structure Practice Problem: Courses and Students (contd.)
struct course{ searchByStudentID (Student st [], int numOfSt, int
char courseId[100]; stId){
double gradePoint ; int i;
}; for(i=0;i<numOfSt;i++){
typedef struct course Course ; if(st[i].id==stId){
struct student{ return i;
char name[100]; }
int id; }
int numCourses ; return -1;
double gpa; }
Course cList [100];
};
typedef struct student Student ;

void sortStudentsByGPA (Student st [], int numOfSt){ void calculateGPA (Student st [], int numOfSt){
int i,j; int n,i;
Student temp ; for(n=0;n<numOfSt;n++){
for(i=0;i<numOfSt-1;i++){ st[n].gpa=0;
for(j=i+1;j<numOfSt;j++){ for(i=0;i<st[n].numCourses ;i++){
if(st[i].gpa<st[j].gpa){ st[n].gpa=st[n].gpa+st[n].cList[i].gradePoint ;
temp =st[i]; }
st [i]=st[j]; st[n].gpa=st[n].gpa/st[n].numCourses ;
st [j]=temp; }
} }
}
}
}
Structure Practice Problem: Books and Bookshops
Struct book {
char title[80];
char author[80];
int isbnNo;
int price;
int copiesSold;
};

struct BookShop {
char name[80];
int numberOfBooks;
struct book books[1000];
};
Functionalities
• Store and process the information of a bookshop
• Add a book to a bookshop
• Search the book with the most copies sold in a bookshop
• Compute the total revenue earned from sale of books in a
bookshop
• Sort the books in a bookshop in the order of price
• Print all the information of a bookshop including details of
the books
Structure Practice Problem: Players and Teams
struct player {
char name[80];
int jersyNo;
int matchPlayer;
int goalScored;
char position[20];
};

struct team {
char name[80];
int matchPlayed;
int matchesWon;
Functionalities int matchesDrawn;
int matchesLost;
• Store and process the information of a football team int totalPoint;
• Add a player to a team struct player players[11];
• Search a player in a team };
• Sort the players in a team in the order of scored goals
• Print all the information of a team including details of
the players
Structure Practice Problem: Points and Rectangles
Functionalities
• Maintain an array of rectangles each identified by two
endpoints of its diagonal.
• Using functions-
• Calculate the length of the diagonal, area and
perimeter of each rectangle
• Sort the rectangles in the order of increasing area
• Check if a point is inside or outside a rectangle
• Check if a rectangle is completely inside, outside or
overlapping with another rectangle
struct point { • Print the of array of rectangles
float x;
float y;
};
typedef struct point Point;

struct rect {
struct point pt1;
struct point pt2;
};
typedef struct rect Rectangle;
Acknowledgement
All these slides of this course have been prepared by taking help from numerous
resources. The notable contributors are listed below.
1. Content and organization of many pages have been taken from the lecture slides and
codes of the course CSE110 offered to the Department of EEE that were -
i. primarily created by Johra Muhammad Moosa, Assistant Professor (on leave),
CSE, BUET and
ii. later modified by Madhusudan Basak, Assistant Professor, CSE, BUET
2. Most of the wonderful coding examples have been taken from the course CSE281
offered to the Department of BME instructed by Rifat Shahriyar, Professor, CSE,
BUET (course link).
3. search and all the sites that it made available in response to the course
related queries. Some of the sites are: https://geeksforgeeks.org/,
https://www.tutorialspoint.com, https://www.w3schools.com and the list goes on

Thank You ☺

You might also like