C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Structures in C

Store book details using structure

C Program: Store and Display Book Details Using Structures

C

#include <stdio.h>

 

// Define structure for book

struct Book {

    int id;

    char title[100];

    char author[100];

    float price;

};

 

// Function declarations

void inputBooks(struct Book books[], int n);

void displayBooks(struct Book books[], int n);

 

int main() {

    struct Book books[100];

    int n;

 

    printf("Enter number of books: ");

    scanf("%d", &n);

 

    // Input and display book details

    inputBooks(books, n);

    displayBooks(books, n);

 

    return 0;

}

 

// Function to input book details

void inputBooks(struct Book books[], int n) {

    for (int i = 0; i < n; i++) {

        printf("\nEnter details of book %d\n", i + 1);

        printf("Enter Book ID: ");

        scanf("%d", &books[i].id);

        getchar(); // clear input buffer

 

        printf("Enter Book Title: ");

        gets(books[i].title);

 

        printf("Enter Author Name: ");

        gets(books[i].author);

 

        printf("Enter Price: ");

        scanf("%f", &books[i].price);

    }

}

 

// Function to display all book details

void displayBooks(struct Book books[], int n) {

    printf("\n===== BOOK DETAILS =====\n");

    for (int i = 0; i < n; i++) {

        printf("\nBook %d\n", i + 1);

        printf("Book ID     : %d\n", books[i].id);

        printf("Title       : %s\n", books[i].title);

        printf("Author      : %s\n", books[i].author);

        printf("Price (₹)   : %.2f\n", books[i].price);

    }

}

Output

 
OUTPUT :
Enter number of books: 2

Enter details of book 1
Enter Book ID: 101
Enter Book Title: C Programming
Enter Author Name: Dennis Ritchie
Enter Price: 499.50

Enter details of book 2
Enter Book ID: 102
Enter Book Title: Data Structures
Enter Author Name: E. Balagurusamy
Enter Price: 599.00

===== BOOK DETAILS =====

Book 1
Book ID     : 101
Title       : C Programming
Author      : Dennis Ritchie
Price (₹)   : 499.50

Book 2
Book ID     : 102
Title       : Data Structures
Author      : E. Balagurusamy
Price (₹)   : 599.00

Explanation

Function

Description

struct Book

Structure with fields — id, title, author, and price.

inputBooks()

Reads book details (loop through array).

displayBooks()

Prints all book records in formatted style.

books[100]

Array of structure to store up to 100 book records.