C Program User Defined Data type – Nested Structure Example

In Nested Structure, variable of user defined type is placed as data member in other user defined type using struct. As example , In struct book, if you want declare data member as purchase date, you can declare other struct type as date which contains day, month, year as data members.

struct date
{
	int day,month,year;
};
struct book
{
	int bid;
	char bnm[20];
	struct date purchase_dt;
	double price;
	int qty;
	double cost;

};

Here first user defined type is date , which as day, month , year as data members. the variable of struct date is declared as data member in other user defined data type book.

#include<stdio.h>
struct date
{
	int day,month,year;
};
struct book
{
	int bid;
	char bnm[20];
	struct date pdt;
	double price;
	int qty;
	double cost;

};

int main()
{

	struct book barray[5];
	int i; double totalcost=0;

	for(i=0;i<4;i++)
	{
		printf("\n\t ENTER BOOK ID: ");	
		scanf("%d",&barray[i].bid);

		printf("\n\t ENTER BOOK NAME: ");	
		scanf("%s",barray[i].bnm);

		printf("\n\t ENTER BOOK PRICE(Rs): ");	
		scanf("%lf",&barray[i].price);

		printf("\n\t ENTER BOOK QTY: ");	
		scanf("%d",&barray[i].qty);

		printf("\n\t ENTER BOOK PURCHASE DATE: ");	
		scanf("%d%d%d",&barray[i].pdt.day,&barray[i].pdt.month,&barray[i].pdt.year);

		barray[i].cost=barray[i].qty*barray[i].price;

		totalcost=totalcost+barray[i].cost;
	}

	printf("\n\tBOOK INFORMATION\n");
	for(i=0;i<4;i++)
	{

		printf("\n\t---------------------------------------------------------------------\n");
		printf("\n\t%2d/%2d/%4d\t",barray[i].pdt.day,barray[i].pdt.month,barray[i].pdt.year);
		printf("%4d\t%5s\t%5.2lf\t%2d\t%5.2lf",barray[i].bid,barray[i].bnm,barray[i].price,barray[i].qty,barray[i].cost);
	}
	printf("\n\n\tTOTAL COST: %6.2lf\n",totalcost);
	printf("\n\n\t-----------------------------------------------digitalpadm.com\n");
}

In this program, barray variable is array of 5 elements of user defined type book. purchase date of each book is read by barray[i].pdt.day, Here day is data member of structure date and pdt is data member of struct book. barray is array variable of struct book, hence it access pdt by member selection operator and pdt access day, month, year by member selection operator.

OUTPUT

output-nested-structure-in-c-program-example

output-nested-structure-in-c-program-example

DOWNLOAD CODE: nested-structure-book-store-example.c (46 downloads)