C Tutorial
Suppose we need to store data of 50 books, we would be required to use 50 different structure variables from b1 to b50, which will not be convenient in better programming.
So an array of structures is the best approach for this situation.
In programming, we usally deal with collection of ints, chars and floats rather than isolated entities.
Example an entity book is a collection of things like a title, an author, total pages, date of publication and price etc..
Structure is user defined data type which combines dissimilar data types into an entity.
This c program shows how to use the array of structures instead of using multiple structure varaibles for the same structure type.
#include<stdio.h> struct book { int id; float price; }; void main() { struct book b[5]; int i, id; float price; int limit = 5; for(i=0;i<limit;i++) { printf("Enter id, and price of book:\n"); scanf("%d", &id); scanf("%f", &price); b[i].id = id; b[i].price = price; } printf("\nbook id\t price \n"); for(i=0;i<limit;i++) { printf("%d\t%f\n", b[i].id, b[i].price); } }
Output:
$ cc structure.c $ ./a.out Enter id, and price of book: 1 34 Enter id, and price of book: 2 34 Enter id, and price of book: 3 34 Enter id, and price of book: 4 65 Enter id, and price of book: 5 78 book id price 1 34.000000 2 34.000000 3 34.000000 4 65.000000 5 78.000000
another example,
#include<stdio.h> struct book { int id; char *title; float price; }; void main() { struct book b[5]; int i, id; char *title; float price; int limit = 1; for(i=0;i<limit;i++) { printf("Enter id, title and price of book:\n"); scanf("%d", &id); scanf("%s", title); scanf("%f", &price); b[i].id = id; b[i].title = title; b[i].price = price; } printf("\nbook id\t title \t price \n"); for(i=0;i<limit;i++) { printf("%d\t%s\t%f\n", b[i].id, b[i].title, b[i].price); } }
Output:
$ cc structure.c $ ./a.out Enter id, title and price of book: 1 book1 32 book id title price 1 book1 32.000000
C Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us
| Report website issues in Github
| Facebook page
| Google+ page