Structure is a collection of logically related data items of different data types grouped
together and known by a single name.
Structure is similar to records in DBMS.
As record consists of fields, the data items of a
structure are called as its members.
Syntax:
struct structure_name
{
datatype-1 variable-1;
datatype-2 variable-2;
.
.
datatype-n variable-n;
};
Here, struct is a
keyword which is used to define a structure template.
struct name is a name
of the structure. It is user defined name.
The members of the
structure are4 written in curly { } braces.
The structure is
terminated by semicolon (;).
Example:
struct student
{
int rollno;
char name[50];
char branch[20];
float per;
}
Accessing the
structure members:
We
can access the individual members of a structure using the dot (.) operator.
The
dot (.) operator is called as structure member operator because it connects the
structure variable and its member’s variable.
Syntax:
struct_variable.struct_member;
Where,
struct_var is a variable of structure type, while struct_member is a name of a
member variable of structure.
Example:
struct student s1;
s1.rollno = 1;
Structure Example:
A
C Program to input and print following details of student using structure.
(roll number, name, address, city, age, per)
#include<conio.h>
#include<stdio.h>
struct
student
{
int rn;
char name[20];
char address[50];
char city[30];
int age;
float per;
}
void
main()
{
struct student s;
clrscr();
printf(“Enter the roll number:”);
scanf(“%d”,&s.rn);
printf(“\n Enter the name:”);
gets(s.name);
printf(“\n Enter the address:”);
gets(s.address);
printf(“\n Enter the city”);
gets(s.city);
printf(“\n
Enter the age:”);
scanf(“%d”,&s.age);
printf(“\n
Enter the percentage:”);
scanf(“%f”, &s.per);
printf(“\n Roll-Number\t Name\t
Address\t City\t Age\t Percentage”);
printf(“\n %d\t %s \t %s \t %s \t %d
\t %f”);
getch();
}
OUTPUT:
Enter
the roll number: 28
Enter
the name: John
Enter
the address: Church Road
Enter
the city: Miami
Enter
the age: 24
Enter
the percentage: 88.00
Roll-Number Name Address City Age Percentage
28 John Church Road Miami 24 88.00
No comments:
Post a Comment