Write a program to read Title, Author and Price of 5 books using array of structures.
Write a program to read Title, Author and Price of 5 books using array of structures. Display the records in ascending order of Price.
Write a program to read Title, Author and Price of 5 books using array of structures. Display the records in ascending order of Price.
#include <stdio.h>
//#include <conio.h>
struct book
{
int price;
char title[80];
char author[80];
};
void accept(struct book list[80]); //func declare
void display(struct book list[80]);
void bsortAsc(struct book list[80]);
void main()
{
struct book data[20];
int n;
//clrscr();
accept(data); //func call
bsortAsc(data);
display(data);
//getch();
}
void accept(struct book list[5]) // func initialize
{
int i;
for (i = 0; i <5; i++)
{
printf("\nEnter title : ");
scanf("%s", &list[i].title);
printf("Enter Author name: ");
scanf("%s",&list[i].author);
printf("Enter price : ");
scanf("%d", &list[i].price);
}
}
void display(struct book list[80])
{
int i;
printf("\n\nTitle\t\tAuthor\t\tprice\n");
printf("-------------------------------------\n");
for (i = 0; i<5; i++)
{
printf("%s\t\t%s\t\t%d\n", list[i].title, list[i].author, list[i].price);
}
}
void bsortAsc(struct book list[80])
{
int i, j;
struct book temp;
for (i = 0; i <5 ; i++)
{
for (j = 0; j < (5 -i); j++)
{
if (list[j].price >list[j + 1].price)
{
temp = list[j];
list[j] = list[j + 1];
list[j + 1] = temp;
}
}
}}The program below reads 5 books into an array of structures, sorts them by price with bubble sort, and prints them in ascending order of price.
#include <stdio.h>
struct book {
char title[50];
char author[50];
float price;
};
int main() {
struct book b[5], temp;
int i, j;
for (i = 0; i < 5; i++) {
printf("Enter title, author and price of book %d: ", i + 1);
scanf("%s %s %f", b[i].title, b[i].author, &b[i].price);
}
/* bubble sort on price */
for (i = 0; i < 5 - 1; i++) {
for (j = 0; j < 5 - 1 - i; j++) {
if (b[j].price > b[j + 1].price) {
temp = b[j];
b[j] = b[j + 1];
b[j + 1] = temp;
}
}
}
printf("\nTitle\tAuthor\tPrice\n");
for (i = 0; i < 5; i++)
printf("%s\t%s\t%.2f\n", b[i].title, b[i].author, b[i].price);
return 0;
}
How it works: struct book groups title, author and price; b[5] is an array of 5 such structures. In bubble sort, the inner loop stops at j < 5 - 1 - i so that b[j + 1] never goes past the last element b[4]. Whole structures can be swapped with one assignment (temp = b[j]), so title and author move together with the price. (%s reads a single word; use scanf(" %[^\n]", ...) for titles with spaces.)
Log in or create a free account to answer this question.