C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Structures and Union in C

Store car details (company, model, price)

C Program: Store and Display Car Details

C

#include <stdio.h>

#include <string.h>

 

// Define structure for Car

struct Car {

    char company[50];

    char model[50];

    float price;

};

 

int main() {

    struct Car c[100];

    int n, i;

 

    printf("Enter number of cars: ");

    scanf("%d", &n);

    getchar(); // clear buffer

 

    // Input car details

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

        printf("\nEnter details for Car %d:\n", i + 1);

 

        printf("Company Name: ");

        gets(c[i].company);

 

        printf("Model Name: ");

        gets(c[i].model);

 

        printf("Price: ");

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

        getchar();

    }

 

    // Display car details

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

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

        printf("\nCar %d Details:\n", i + 1);

        printf("Company : %s\n", c[i].company);

        printf("Model   : %s\n", c[i].model);

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

    }

 

    return 0;

}

Output

 
OUTPUT :

Enter number of cars: 2

Enter details for Car 1:
Company Name: Toyota
Model Name: Fortuner
Price: 4200000

Enter details for Car 2:
Company Name: Tesla
Model Name: Model S
Price: 9500000

===== CAR DETAILS =====

Car 1 Details:
Company : Toyota
Model   : Fortuner
Price   : 4200000.00

Car 2 Details:
Company : Tesla
Model   : Model S
Price   : 9500000.00

Explanation

Concept

Description

struct Car

Defines the car structure with company, model, and price.

c[100]

Array of car structures for multiple entries.

gets()

Reads string input for company and model. (Can replace with fgets() for safety.)

for loop

Takes input and displays data for each car.