Structure is the collection of variables of different types.
Structure is user defined data type available in C that allows combining data items of different kinds.
Structures are used to represent a record. Suppose you want to keep track of your books in a library. You might want to track the following attributes about each book −
· Title
· Book ID
· Book Price
Syntax:
|
Example:
|
struct structure_name
{
data_type member1;
data_type member2;
.
data_type memeber;
}struct_variable;
|
struct book
{
char title[20];
int book_id;
float price;
}bk1,bk2; //structure variable
|
In above example bk1, bk2 are the structure variable.
At the end of the structure's definition, before the final semicolon, you can specify one or more structure variables but it is optional it can be also declared inside main like
//inside main
struct book bk1,bk2; //structure variable
There are two types of operators used for accessing members of a structure.
-Member operator (.)
Any member of a structure can be accessed as:
structure_variable.member1
structure_variable.member2
For example
bk1.title, bk1.book_id, bk1.price
Example of Structure
#include <stdio.h>
#include <stdio.h>
struct book
{
char title[20];
int book_id;
float price;
}bk1; //struct variable
void main()
{
clrscr();
printf("Insert book details\n");
printf("Enter book name: ");
scanf("%s",&bk1.title); // input title of book
printf("Enter book id: ");
scanf("%d",&bk1.book_id); // input id of book
printf("Enter price");
scanf("%f",&bk1.price); // input price of book
printf(“Book Detail”);
printf(“\nTitle ID Price”);
printf(“\n%s %d %f”, bk1.title, bk1.book_id, bk1.price);
getch();
}
|
#include <stdio.h>
#include <stdio.h>
struct book
{
char title[20];
int book_id;
float price;
};
void main()
{
struct book bk1; //struct variable
clrscr();
printf("Insert book details\n");
printf("Enter book name: ");
scanf("%s",&bk1.title); //input title of book
printf("Enter book id: ");
scanf("%d",&bk1.book_id); // input id of book
printf("Enter price");
scanf("%f",&bk1.price); // input price of book
printf(“Book Detail”);
printf(“\nTitle ID Price”);
printf(“\n%s %d %f”, bk1.title, bk1.book_id, bk1.price);
getch();
}
|
0 comments:
Post a Comment