Structure is a collection of different datatype variables, grouped together under a single name.
Features of structure
The features of structure in the C programming language are as follows −
It is possible to copy the contents of all the structure elements of different datatypes to another structure variable of its type by using an assignment operator.
For handling the complex datatypes, it is better to create structure within another structure, which is called nested structures.
It is possible to pass an entire structure, individual elements of structure and an address of structure to a function.
It is possible to create structure pointers.
Program
Following is the C program to store an inventory system by using the structures −
#include<stdio.h> #include<conio.h> void main(){ struct date{ int day; int month; int year; }; struct details{ char name[20]; int price; int code; int qty; struct date mfg; }; struct details item[50]; int n,i; printf("Enter number of items:"); scanf("%d",&n); fflush(stdin); for(i=0;i<n;i++){ fflush(stdin); printf("Item name:"); scanf("%s",item[i].name); fflush(stdin); printf("Item code:"); scanf("%d",&item[i].code); fflush(stdin); printf("Quantity:"); scanf("%d",&item[i].qty); fflush(stdin); printf("price:"); scanf("%d",&item[i].price); fflush(stdin); printf("Manufacturing date(dd-mm-yyyy):"); scanf("%d-%d-%d",&item[i].mfg.day,&item[i].mfg.month,&item[i].mfg.year); } printf(" ***** INVENTORY *****\n"); printf("------------------------------------------------------------------\n"); printf("S.N.| NAME | CODE | QUANTITY | PRICE |MFG.DATE\n"); printf("------------------------------------------------------------------\n"); for(i=0;i<n;i++) printf("%d %-15s %-d %-5d %-5d%d/%d/%d\n",i+1,item[i].name,item[i].code,item[i].qty,item[i].price,item[i].mfg.day,item[i].mfg.month,item[i].mfg.year); printf("------------------------------------------------------------------\n"); getch(); }
Output
When the above program is executed, it produces the following result −
Enter number of items:5 Item name:pen Item code:12 Quantity:50 price:25 Manufacturing date(dd-mm-yyyy):12-02-2020 Item name:pencil Item code:15 Quantity:100 price:30 Manufacturing date(dd-mm-yyyy):11-03-2020 Item name:book Item code:34 Quantity:30 price:60 Manufacturing date(dd-mm-yyyy):15-04-2020 Item name:bag Item code:39 Quantity:20 price:70 Manufacturing date(dd-mm-yyyy):12-03-2021 Item name:sharpner Item code:33 Quantity:20 price:40 Manufacturing date(dd-mm-yyyy):12-04-2021 ***** INVENTORY ***** ------------------------------------------------------------------ S.N.| NAME | CODE | QUANTITY | PRICE |MFG.DATE ------------------------------------------------------------------ 1 pen 12 50 25 12/2/2020 2 pencil 15 100 30 11/3/2020 3 book 34 30 60 15/4/2020 4 bag 39 20 70 12/3/2021 5 sharpner 33 20 40 12/4/2021