Creating a Groceries Shopping Program with Invoice Printing using C language: Step-by-Step Guide


C programming language

In this tutorial, we will walk through the process of creating a simple shopping center program using the C programming language. The program will allow users to select and purchase different products, generate an invoice, and keep track of the total purchase amount. We'll use sequential file handling, array sorting, loops, and all this would be done using the Code::Blocks IDE.

Prerequisites

Before we begin, make sure you have a basic understanding of the C programming language. Additionally, ensure that you have the Code::Blocks Integrated Development Environment (IDE) installed on your system. Code::Blocks provides a user-friendly interface for writing, compiling, and running C programs.

If you haven't installed Code::Blocks, you can download it from the official website: Code::Blocks Download Page. Follow the installation instructions for your operating system.

Once you have Code::Blocks installed, you're ready to proceed with creating the shopping center program. Let's dive into the step-by-step guide!

Step 1: Initialize Arrays and Naming Variables

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 1 of the shopping products. The aim of this program
is to use sequential file system to generate an invoice.
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,
and print an invoice. */
// File shopping_products.c

#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
    float balance = 0;

Step 2: Generate Invoice with Current Time and Date

We'll generate the initial part of the invoice, including the shopping center's details and the current date and time. For the invoice, 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 the opening the invoice 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\\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\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, "\n\tItem\t\tPrice(USD)\n");
    fprintf(fShop, "--------------------------------------\n");
    fclose(fShop); // close the file

Step 3: Shopping Loop

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 invoice will be the final balance before the loop was ended.

  • 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("\n\n\tItem\t\tPrice(USD)\n");
            printf("------------------------------------\n");
            printf("\t%s\t\t%.2f\n", product[ctr], prices[ctr]);
            printf("------------------------------------\n");
            balance += prices[ctr];
            printf("\tBalance: %.2f\n", balance);
            printf("-------------------------------------\n\n");
            printf("Thanks for shopping with us!\n");

            // code to open and update 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%.2f\n", product[ctr], prices[ctr]);
            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);
   

Step 4: Print Invoice

After the user has finished shopping, we'll add the final balance and print the invoice.

  • Leave a line after the previous code and type the following code to conclude the generated invoice
// code to update the generated the 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, "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 and What's Next

Congratulations! You've successfully created a simple groceries shopping center program in C using the Code::Blocks IDE. This program demonstrates the use of arrays, loops, and file handling to manage product information, generate invoices, and calculate purchase totals.

In the upcoming second part of this tutorial, we'll explore how to enhance the program's functionality. We'll dive into the sequential file system to generate comprehensive receipts that not only display the items purchased but also include the total balance, the amount paid by the customer, and the change given. This additional feature will provide a more realistic shopping experience in our program.

Just like in this part of the tutorial, we'll continue to utilize array sorting to manage product information, parallel arrays to store product names and prices, and the power of loops to handle various customer purchases. By the end of the series, you'll have a fully functional and feature-rich shopping center program that you can use as a foundation for even more complex projects.

So stay tuned for the next installment, where we'll explore the world of receipts and advanced features to bring our shopping center program to life!

If you have any questions, comments, or suggestions, feel free to reach out in the comments section on our social media page. Happy coding!