Creating a Shopping Program with Receipt Printing with C language: Part 2 - Creating Detailed Receipts

C program

Introduction

In Part 1 of our tutorial, we laid the foundation for a simple shopping center program in C using the Code::Blocks IDE. Now, in Part 2, we're taking things a step further by enhancing our program to generate not just an invoice but a comprehensive receipt. This receipt will include vital details such as the total balance, the amount paid by the customer, and the change given to the customer. 

Prerequisites

Before diving into this part of the tutorial, make sure you've completed Part 1; Creating a Groceries Shopping Program with Invoice Printing using C language: Step-by-Step Guide, where we covered the basics of creating a shopping program. Creating a Groceries Shopping Program with Invoice Printing using C language: Step-by-Step Guide . Additionally, ensure that you have Code::Blocks installed on your system. If not, you can download it from the official Code::Blocks Download Page.

Understanding the Code

Let's explore the code that powers our enhanced shopping program step by step:

Initialization and Data Arrays

Like the first part, we start by initializing three arrays: `pNumber` to hold product numbers, `prices` to store product prices, and `product` to store product names. These arrays will be used to maintain the product database, after which we would add other variables relevant to the program. 

Note: This array holds only 10 variables, you can add more if you like. Also note that all the code in this program will be within the main () function.

  • Open your code::blocks IDE and click on the file in the menu bar, then click on New, and click on Empty file.
  • save the Untitled file using ctrl+S, using the file name shopping_products.c
  • After saving the file, Type the following code, to initialize the parallel arrays, and name the different variables for the program
/*This is the part 3 of the shopping products. The aim of this program
is to use sequential file system to generate not just an invoice, but a
receipt, which will contain the total balance, the amount paid by the
customer, and the change given to the customer.
The program uses array sorting to hold the product number for
each product. A parallel array is used to hold the name and price
of each product. A do while loop is used to add the total purchase,
based on the number of quantity the customer purchase
and output an invoice. And then the amount paid by the customer is
then received and the change calculated. */

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
FILE * fShop;

int main()
{
    int pNumber[10] = {110, 111, 112, 113, 114, 115, 116, 117, 118, 119};
    float prices[10] = {220.12, 312.60, 107.20, 1134.51, 103.63, 45.89,
                    34.79, 89.23, 674.80, 723.00};
    char * product[10] = {"ice-cream", "chocolate bar", "bread", "kellogg flakes",
                            "liquid milk", "corn chips", "sugar", "cookies",
                            "Eva wine", "butter"};

    int ctr; // to hold the loop during search
    int search; // to search for the product number
    int found = 0; // will become 1 (true) if a product is found
    int pick; // loop to continue adding more items
    int quantity; // to hold the quantity of items purchased
    float total; // to hold the multiplication of price and quantity
    float balance = 0;
    float paid; // to receive money from the customer
    float change; // the change to be given to the customer

Generating the Receipt

We create the framework for our receipt, including the shopping center's details and the current date and time: For the receipt, we use the C language sequential files append (a) mode. Recall, during the function declaration, we declared the file pointer "FILE * fShop;"

  • We first need to add an introductory message for the loop, before we generate the receipt file
  • Immediately after the previous code you typed, leave a line and type the following code.

    time_t t;
    time(&t);

    printf("INSTRUCTION: PLEASE PRESS 1, IF YOU ARE READY TO START ADDING ITEMS: ");
    scanf(" %d", &pick);

    // code to generate the receipt
    fShop = fopen("C:\\users\\FAVOUR\\Desktop\\codes\\shoppingReceipt.txt", "a");
    // if the receipt generation fails
    if (fShop == 0)
    {
        printf("Error---Receipt could not be generated.\n");
        exit(1);
    }
    // code to print receipt
    fprintf(fShop, "\n\tMICHELLO SHOPPING CENTER\n");
    fprintf(fShop, "\tAddress: 156B Lake-Side Lane\n\n");
    fprintf(fShop, "\tDate and Time: %s\n", ctime(&t));
    fprintf(fShop, "------------------------------------------\n");
    fprintf(fShop, "Customer's Receipt\n");
    fprintf(fShop, "------------------------------------------\n");
    fprintf(fShop, "\n\tItem\t\tQuantity\tPrice(USD)\n");
    fprintf(fShop, "------------------------------------------\n");
    fclose(fShop); // close the file

This code sets up the receipt structure, including time, headers and separators.

Shopping Loop and Quantity Calculation

We implement a loop that allows users to input a product number, searches for the product in the database, and updates the invoice accordingly. At every product number input, the new total balance is shown on the screen, but the total balance on the receipt will be the final balance before the loop end. 

  • The following code shows the loop for adding the product number to display the items and the various price, and updating the invoice as the product number is being inputted 
  • Immediately after the previous code you type, leave a line and type the following code 
 do
    {
        // code to collect 3 digit product number
        printf("\n\nInput 3 digit product number: ");
        scanf(" %d", &search);

        // search to identify the product in your database
        for (ctr = 0; ctr < 10; ctr++)
        {
            if (search == pNumber[ctr])
            {
                found = 1;
                break;
            }
        }

        // bring out the product name and price
        if (found)
        {
            printf("Enter the Quantity of %s: ", product[ctr]);
            scanf(" %d", &quantity);
            total = prices[ctr] * quantity;
            printf("\n\n\tItem\t\tQuantity\tPrice(USD)\n");
            printf("-----------------------------------------------\n");
            printf("\t%s\t\t%d\t%.2f\n", product[ctr], quantity, total);
            printf("-----------------------------------------------\n");
            balance += total;
            printf("\tBalance: %.2f\n", balance);
            printf("------------------------------------------------\n\n");
            printf("Thanks for shopping with us!\n");

            // code to open and add to the generated receipt
            fShop = fopen("C:\\users\\FAVOUR\\Desktop\\codes\\shopping.txt", "a");
            // if the receipt generation fails
            if (fShop == 0)
            {
                printf("Error---Receipt could not be generated.\n");
                exit(1);
            }
            // code to print receipt
            fprintf(fShop, "\t%s\t\t%d\t%.2f\n", product[ctr], quantity, total);
            fclose(fShop); //close the file
        }
        else
        {
            printf("This item is not available!!!");
            exit(1);
        }

        printf("To add another item, press 1: ");
        scanf(" %d", &pick);

    } while (pick == 1);

In this section, the program ensures that the product exists in the database, calculates the total based on the quantity, and keeps track of the balance.

Payment and Change Calculation

In this section, after customers have completed their shopping, they enter the amount paid. The program then calculates and displays the change:

// Accept money from the customer
    printf("Enter Amount paid by customer (xx.xx): ");
    scanf(" %f", &paid);
    change = paid - balance;
    printf("Customer's Change is: %.2f", change);

This final step handles the financial aspects of the transaction.

Generate the Final Part of the Receipt

The finial part of the receipt includes the balance, money paid by the customer and the change received as calculated above. 

  • Leave a line after the previous code and type the following code to conclude the generated invoice
 // code to add to the generated receipt
        fShop = fopen("C:\\users\\FAVOUR\\Desktop\\codes\\shopping.txt", "a");
        // if the receipt generation fails
        if (fShop == 0)
        {
            printf("Error---Receipt could not be generated.\n");
            exit(1);
        }
        // code to print receipt
        fprintf(fShop, "-------------------------------------------\n");
        fprintf(fShop, "\tBalance: %.2f\n", balance);
        fprintf(fShop, "-------------------------------------------\n");
        fprintf(fShop, "\tAmount Paid: %.2f\n", paid);
        fprintf(fShop, "\tYour Change: %.2f\n", change);
        fprintf(fShop, "-------------------------------------------\n");
        fprintf(fShop, "Thanks for shopping with us");
        fprintf(fShop, "\n\n");
        fclose(fShop); // close the file

    printf("\n\nRun the program again when you are ready!!\n\n");
    return(0);
}
 
  • Click on ctrl+S to save the file 
  • You can test your program by clicking on the yellow wrench icon with a green play button as shown in the image below:
the run button

The video below will show you the full code and how the program works.

Conclusion

In this part of our tutorial, we've transformed our basic shopping program into a more sophisticated tool capable of generating detailed receipts. Customers can now shop, receive an itemized receipt, and even calculate change.

Feel free to explore the code further, experiment, and customize it to suit your specific needs. Happy coding!