Академический Документы
Профессиональный Документы
Культура Документы
7
To study and perform program based on the use of Structures.
Theory:
C Structure is a collection of different data types which are grouped together and each element in
a C structure is called member.
Syntax:
struct tag_name
{
data type var_name1;
data type var_name2;
data type var_name3;
};
Example:
struct student
{
int mark;
char name[10];
float average;
};
#include <stdio.h>
1
#include <string.h>
2
3
struct student
4
{
5
int id;
6
char name[20];
7
float percentage;
8
};
9
10
int main()
11
{
12
struct student record = {0}; //Initializing to null
13
14
record.id=1;
15
strcpy(record.name, "Raju");
16
record.percentage = 86.5;
17
18
printf(" Id is: %d \n", record.id);
19
printf(" Name is: %s \n", record.name);
20
printf(" Percentage is: %f \n", record.percentage);
21
return 0;
22
}
23
OUTPUT:
Id is: 1
Name is: Raju
Percentage is: 86.500000
Array of Structures:
C Structure is collection of different datatypes ( variables ) which are grouped together. Whereas,
array of structures is nothing but collection of structures. This is also called as structure array in
C.
2 #include <string.h>
4 struct student
5 {
6 int id;
7 char name[30];
8 float percentage;
9 };
10
11 int main()
12 {
13 int i;
15
17 record[0].id=1;
18 strcpy(record[0].name, "Raju");
19 record[0].percentage = 86.5;
20
22 record[1].id=2;
23 strcpy(record[1].name, "Surendren");
24 record[1].percentage = 90.5;
25
27 record[2].id=3;
28 strcpy(record[2].name, "Thiyagu");
29 record[2].percentage = 81.5;
30
32 {
37 }
38 return 0;
39 }
OUTPUT:
Records of STUDENT : 1
Id is: 1
Name is: Raju
Percentage is: 86.500000
Records of STUDENT : 2
Id is: 2
Name is: Surendren
Percentage is: 90.500000
Records of STUDENT : 3
Id is: 3
Name is: Thiyagu
Percentage is: 81.500000
#include <stdio.h>
struct Distance
int feet;
float inch;
int main()
scanf("%d", &d1.feet);
scanf("%f", &d1.inch);
scanf("%d", &d2.feet);
sumOfDistances.feet = d1.feet+d2.feet;
sumOfDistances.inch = d1.inch+d2.inch;
if (sumOfDistances.inch>12.0)
sumOfDistances.inch = sumOfDistances.inch-12.0;
++sumOfDistances.feet;
return 0;
Output
Enter feet: 23
Enter feet: 34
Two variables (d1 and d2) are created which stores two distances (in inch and feet). Then, the
sum of two distances is stored in sumOfDistances structure and displayed on the screen.
Conclusion:
In this way we had studied and perform program based on structure.