Day 6.
Structures
Structures
In general, we can call a structure is a collection of different types of data. A Structure contains number of data types grouped together. These data types may be or may not be of same data type.
‘C’ implementation of Structure. •
The keyword ‘struct’ is used for creating a structure. Syntax: struct structure-name { datatype1 varname1; datatype1 varname2; datatype1 varname3; }; creating the object of structure: struct structure-name var1, var2, var3;
Accessing structure elements. . (dot operator) is used to access individual structure element. e.g. struct list { int roll; char name[10]; float marks; }; struct list a , b , c; a.roll – is the integer element of structure a. a.name – is char array element of structure a b.marks – is a float element of structure b. a.marks – is a float element of structure b. scanf(“%d”, &b.roll); this statement can accept an integer roll of structure b from user. This is applied to all the elements of a structure.
How structure elements are stored. e.g. struct book { char name; int pages; float price; }; struct book z = {‘s’, 125, 90.0}; Here value of : z.name is ‘s’. z.pages is 125 and z.price is 90.0 Memory map:
z.name
‘s’
z.pages
125
z.price
90.0
Valid declaration. struct list { int roll; char name[10]; float marks; }; struct list a , b , c; It is equivalent to : struct list { int roll; char name[10]; float marks; }a, b, c;
Remember: ¾
¾
¾
The closing bracket of structure type declaration must be followed by a semicolon. Usually structure declaration appears at the top of the source code file before any variables and structures are defined. Accessing single variable in a structures must be followed by a . (dot operator).
Example: Creating a student database of 3 students. #include<stdio.h> void main( ) { struct student {
int roll; char name[10]; float marks; } a, b, c; printf(“Enter all information of students:” ); scanf(“%d %s %f”, &a.roll, a.name, &a.marks); scanf(“%d %s %f”, &b.roll, b.name, &b.marks); scanf(“%d %s %f”, &c.roll, c.name, &c.marks);
}
printf(“You entered this information:”); printf(“\n%d %s %f”, a.roll, a.name, a.marks); printf(“\n%d %s %f”, b.roll, b.name, b.marks); printf(“\n%d %s %f”, c.roll, c.name, c.marks);
Array of structures. ¾
We can create the array of structures. Thus, we can use the same structure for more than one variables which adds more flexibility in your program. Let’s view the previous example.
#include<stdio.h> void main( ) { struct student { int roll; char name[10]; float marks; } a[10]; int j; printf(“Enter all information of students:” ); for(j = 0 ; j < 10 ; j++) scanf(“%d %s %f”, &a.roll[i], a.name[i], &a.marks[i]); for(j = 0 ; j < 10 ; j++) printf(“\n%d %s %f”, a.roll[i], a.name[i], a.marks[i]); }
Memory map for arrays. a[i].roll
i
a[i].name a[i].marks 0 1 2 3
a[5].roll
4 5 6 7 8 9
a[9].name
Created By,
Mr. Tushar B Kute, Lecturer in Information Technology, K. K. Wagh Polytechnic, Nashik.
[email protected]