Professional Documents
Culture Documents
Structure
Structure
Computer Programming
Lecture 8:
Structures in C
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
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.
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;
}
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;
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 ☺