C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Structures and Union in C

Online shopping cart using structures

C Program: Online shopping cart using structures

C

#include <stdio.h>

 

struct Item {

    int id;

    char name[50];

    float price;

    int quantity;

    float total;

};

 

int main() {

    struct Item cart[100];

    int n, i;

    float grandTotal = 0.0;

 

    printf("Enter number of items to add to cart: ");

    scanf("%d", &n);

 

    // Input item details

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

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

 

        printf("Item ID: ");

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

        getchar();

 

        printf("Item Name: ");

        gets(cart[i].name);

 

        printf("Price: ");

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

 

        printf("Quantity: ");

        scanf("%d", &cart[i].quantity);

 

        cart[i].total = cart[i].price * cart[i].quantity;

        grandTotal += cart[i].total;

    }

 

    // Display cart details

    printf("\n================== SHOPPING CART ==================\n");

    printf("%-5s %-20s %-10s %-10s %-10s\n", "ID", "Item Name", "Price", "Qty", "Total");

    printf("---------------------------------------------------\n");

 

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

        printf("%-5d %-20s %-10.2f %-10d %-10.2f\n",

               cart[i].id, cart[i].name, cart[i].price,

               cart[i].quantity, cart[i].total);

    }

 

    printf("---------------------------------------------------\n");

    printf("Grand Total: %.2f\n", grandTotal);

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

 

    return 0;

}

Output

 
OUTPUT :
Enter number of items to add to cart: 3

Enter details for Item 1:
Item ID: 101
Item Name: Keyboard
Price: 799
Quantity: 2

Enter details for Item 2:
Item ID: 102
Item Name: Mouse
Price: 499
Quantity: 1

Enter details for Item 3:
Item ID: 103
Item Name: Headphones
Price: 1299
Quantity: 1

================== SHOPPING CART ==================
ID    Item Name           Price      Qty        Total     
---------------------------------------------------
101   Keyboard            799.00     2          1598.00   
102   Mouse               499.00     1          499.00    
103   Headphones          1299.00    1          1299.00   
---------------------------------------------------
Grand Total: 3396.00
===================================================

Explanation

Concept

Description

struct Item

Stores product details such as ID, name, price, and quantity.

cart[100]

Array of items to simulate a shopping cart.

total

Computed as price × quantity for each item.

grandTotal

Sum of all item totals.

gets()

Reads item names (you can replace with fgets() for safety).