C Program To Make Bill Statement
Creating a bill statement program in C involves handling customer details, item specifics, and calculating totals. In this article, you will learn how to build a basic bill statement program in C that captures itemized purchases and computes the final amount payable.
Problem Statement
Businesses frequently need to generate clear and accurate bill statements for their customers. This involves recording details such as the customer's name, individual items purchased, their quantities, unit prices, and then calculating a subtotal, applying taxes or discounts, and arriving at a grand total. Manually performing these calculations can be error-prone and time-consuming, highlighting the need for an automated solution.
Example
Here's an example of what a simple C bill statement program might output:
Welcome to Our Store!
Customer Name: John Doe
----------------------------------------
Item Qty Price Total
----------------------------------------
Laptop 1 1200.00 1200.00
Mouse 2 25.00 50.00
Keyboard 1 75.00 75.00
----------------------------------------
Subtotal: 1325.00
Tax (10%): 132.50
Discount (5%): 66.25
----------------------------------------
Total Payable: 1391.25
Background & Knowledge Prerequisites
To effectively understand and implement the solutions in this article, you should have a basic understanding of:
- C Language Fundamentals: Variables, data types (e.g.,
int,float,char[]), and basic arithmetic operations. - Input/Output Operations: Using
printf()for displaying output andscanf()for reading user input. - Control Flow: Basic concepts of
if-elsestatements for conditional logic andwhileorforloops for repetition. - Standard Libraries: Familiarity with
#includefor standard input/output functions.
Use Cases
Bill statement programs are essential in various scenarios:
- Retail Outlets: Generating receipts for customer purchases at grocery stores, electronics shops, or clothing boutiques.
- Restaurants and Cafes: Itemizing food and beverage orders and calculating the total bill, including service charges.
- Service Providers: Billing clients for services rendered, such as hourly consulting, repairs, or maintenance.
- Online Platforms: Creating invoices for digital product sales or subscription services.
- Educational Institutions: Generating fee challans for tuition, examination fees, or hostel charges.
Solution Approaches
We will explore three progressive approaches to building a bill statement program in C, starting with a basic fixed-item structure and advancing to a more dynamic and feature-rich version.
Approach 1: Basic Fixed-Item Bill
This approach demonstrates the simplest way to create a bill for a few predefined items, taking quantities and prices as input.
One-line summary: Calculates a bill for a fixed number of items by manually inputting quantities and their respective unit prices.
Code Example:
// Basic Fixed-Item Bill
#include <stdio.h>
int main() {
// Step 1: Declare variables for item details and calculations
char customerName[50];
int qtyLaptop, qtyMouse, qtyKeyboard;
float priceLaptop = 1200.00;
float priceMouse = 25.00;
float priceKeyboard = 75.00;
float totalLaptop, totalMouse, totalKeyboard, subtotal;
// Step 2: Get customer name
printf("Enter Customer Name: ");
// Use fgets to safely read a line of text including spaces
// stdin is the standard input stream
// 49 is the max characters to read (50 - 1 for null terminator)
fgets(customerName, sizeof(customerName), stdin);
// Remove the trailing newline character if present
for (int i = 0; customerName[i] != '\\0'; i++) {
if (customerName[i] == '\\n') {
customerName[i] = '\\0';
break;
}
}
// Step 3: Get quantities for each item
printf("Enter Quantity for Laptop (%.2f each): ", priceLaptop);
scanf("%d", &qtyLaptop);
printf("Enter Quantity for Mouse (%.2f each): ", priceMouse);
scanf("%d", &qtyMouse);
printf("Enter Quantity for Keyboard (%.2f each): ", priceKeyboard);
scanf("%d", &qtyKeyboard);
// Step 4: Calculate total for each item
totalLaptop = qtyLaptop * priceLaptop;
totalMouse = qtyMouse * priceMouse;
totalKeyboard = qtyKeyboard * priceKeyboard;
// Step 5: Calculate subtotal
subtotal = totalLaptop + totalMouse + totalKeyboard;
// Step 6: Print the bill statement
printf("\\n--- Bill Statement ---\\n");
printf("Customer Name: %s\\n", customerName);
printf("----------------------------------------\\n");
printf("%-15s %-5s %-10s %-10s\\n", "Item", "Qty", "Price", "Total");
printf("----------------------------------------\\n");
printf("%-15s %-5d %-10.2f %-10.2f\\n", "Laptop", qtyLaptop, priceLaptop, totalLaptop);
printf("%-15s %-5d %-10.2f %-10.2f\\n", "Mouse", qtyMouse, priceMouse, totalMouse);
printf("%-15s %-5d %-10.2f %-10.2f\\n", "Keyboard", qtyKeyboard, priceKeyboard, totalKeyboard);
printf("----------------------------------------\\n");
printf("%-32s %-10.2f\\n", "Subtotal:", subtotal);
printf("----------------------------------------\\n");
return 0;
}
Sample Output:
Enter Customer Name: Jane Doe
Enter Quantity for Laptop (1200.00 each): 1
Enter Quantity for Mouse (25.00 each): 2
Enter Quantity for Keyboard (75.00 each): 1
--- Bill Statement ---
Customer Name: Jane Doe
----------------------------------------
Item Qty Price Total
----------------------------------------
Laptop 1 1200.00 1200.00
Mouse 2 25.00 50.00
Keyboard 1 75.00 75.00
----------------------------------------
Subtotal: 1325.00
----------------------------------------
Stepwise Explanation:
- Variable Declaration: We declare variables for the customer's name, quantities of specific items, their fixed prices, and variables to store individual item totals and the overall subtotal.
- Customer Name Input:
fgetsis used to read the customer's name, including spaces, ensuring safer input handling thanscanffor strings. A loop then removes the trailing newline character thatfgetsincludes. - Quantity Input: The program prompts the user to enter the quantity for each item (Laptop, Mouse, Keyboard) using
scanf(). - Item Total Calculation: For each item, its total cost is calculated by multiplying its quantity by its unit price.
- Subtotal Calculation: All individual item totals are summed up to get the
subtotal. - Bill Output: Finally,
printf()statements are used to display the customer's name, a formatted table of items with their quantities, prices, and totals, and the calculated subtotal. Formatting specifiers like%-15sand%-10.2fare used to align text and numbers.
Approach 2: Bill with Multiple Items (Loop-based Input)
This approach enhances the previous one by allowing the user to input details for multiple items dynamically until they choose to stop.
One-line summary: Generates a bill by repeatedly prompting the user for item name, quantity, and price, accumulating the total until the user decides to finish.
Code Example:
// Dynamic Item Bill
#include <stdio.h>
#include <string.h> // Required for strcmp
int main() {
// Step 1: Declare variables
char customerName[50];
char itemName[30];
int qty;
float price, itemTotal;
float subtotal = 0.0;
char addMore = 'y'; // Control variable for loop
// Step 2: Get customer name
printf("Enter Customer Name: ");
fgets(customerName, sizeof(customerName), stdin);
for (int i = 0; customerName[i] != '\\0'; i++) {
if (customerName[i] == '\\n') {
customerName[i] = '\\0';
break;
}
}
// Step 3: Print bill header
printf("\\n--- Bill Statement ---\\n");
printf("Customer Name: %s\\n", customerName);
printf("----------------------------------------\\n");
printf("%-15s %-5s %-10s %-10s\\n", "Item", "Qty", "Price", "Total");
printf("----------------------------------------\\n");
// Step 4: Loop to get multiple item details
while (addMore == 'y' || addMore == 'Y') {
// Clear input buffer before reading new string
// while (getchar() != '\\n'); // Might be needed if previous scanf left newline
printf("Enter Item Name (or type 'done' to finish): ");
fgets(itemName, sizeof(itemName), stdin);
for (int i = 0; itemName[i] != '\\0'; i++) {
if (itemName[i] == '\\n') {
itemName[i] = '\\0';
break;
}
}
if (strcmp(itemName, "done") == 0 || strcmp(itemName, "Done") == 0) {
break; // Exit loop if user types 'done'
}
printf("Enter Quantity for %s: ", itemName);
scanf("%d", &qty);
printf("Enter Price per unit for %s: ", itemName);
scanf("%f", &price);
// Clear input buffer after scanf for numbers
while (getchar() != '\\n');
// Calculate item total
itemTotal = qty * price;
subtotal += itemTotal; // Add to running subtotal
// Print item details in the bill
printf("%-15s %-5d %-10.2f %-10.2f\\n", itemName, qty, price, itemTotal);
printf("Add another item? (y/n): ");
scanf(" %c", &addMore); // Space before %c to consume any leftover newline
while (getchar() != '\\n'); // Clear input buffer
}
// Step 5: Print subtotal and footer
printf("----------------------------------------\\n");
printf("%-32s %-10.2f\\n", "Subtotal:", subtotal);
printf("----------------------------------------\\n");
return 0;
}
Sample Output:
Enter Customer Name: Mark Johnson
--- Bill Statement ---
Customer Name: Mark Johnson
----------------------------------------
Item Qty Price Total
----------------------------------------
Enter Item Name (or type 'done' to finish): T-Shirt
Enter Quantity for T-Shirt: 2
Enter Price per unit for T-Shirt: 15.50
T-Shirt 2 15.50 31.00
Add another item? (y/n): y
Enter Item Name (or type 'done' to finish): Jeans
Enter Quantity for Jeans: 1
Enter Price per unit for Jeans: 45.00
Jeans 1 45.00 45.00
Add another item? (y/n): y
Enter Item Name (or type 'done' to finish): Socks
Enter Quantity for Socks: 3
Enter Price per unit for Socks: 5.00
Socks 3 5.00 15.00
Add another item? (y/n): n
----------------------------------------
Subtotal: 91.00
----------------------------------------
Stepwise Explanation:
- Variable Declaration: Similar variables as before, but also
addMoreto control a loop anditemTotalfor each item's individual calculation. - Customer Name Input: Same as Approach 1.
- Bill Header: Prints the initial part of the bill, including the customer's name and table headers.
- Loop for Item Details: A
whileloop continues as long as the user wants to add more items.
- Inside the loop, the program prompts for the item name, quantity, and price.
-
fgetsis used for the item name, andstrcmpchecks if the user typed "done" to exit the loop. -
scanfis used for numerical inputs. Crucially,while (getchar() != '\n');is used afterscanfcalls to clear the input buffer of any leftover newline characters, which prevents issues with subsequentfgetscalls. A space before%cinscanf(" %c", &addMore);also helps consume whitespace. - Each item's total is calculated and added to the
subtotal. - The item's details are immediately printed to the bill format.
- The user is asked if they want to add another item.
- Subtotal and Footer: After the loop finishes, the final
subtotalis printed, concluding the bill statement.
Approach 3: Enhanced Bill with Tax and Discount
This approach expands on the dynamic item input by incorporating calculations for sales tax and potential discounts, providing a more comprehensive bill.
One-line summary: Creates a dynamic item bill that calculates subtotal, applies a tax rate, subtracts a discount, and displays the final total payable.
Code Example:
// Enhanced Bill with Tax and Discount
#include <stdio.h>
#include <string.h> // Required for strcmp
int main() {
// Step 1: Declare variables
char customerName[50];
char itemName[30];
int qty;
float price, itemTotal;
float subtotal = 0.0;
float taxRate = 0.10; // 10% tax
float discountRate = 0.05; // 5% discount
float taxAmount, discountAmount, totalPayable;
char addMore = 'y';
// Step 2: Get customer name
printf("Enter Customer Name: ");
fgets(customerName, sizeof(customerName), stdin);
for (int i = 0; customerName[i] != '\\0'; i++) {
if (customerName[i] == '\\n') {
customerName[i] = '\\0';
break;
}
}
// Step 3: Print bill header
printf("\\n--- Bill Statement ---\\n");
printf("Customer Name: %s\\n", customerName);
printf("----------------------------------------\\n");
printf("%-15s %-5s %-10s %-10s\\n", "Item", "Qty", "Price", "Total");
printf("----------------------------------------\\n");
// Step 4: Loop to get multiple item details
while (addMore == 'y' || addMore == 'Y') {
printf("Enter Item Name (or type 'done' to finish): ");
fgets(itemName, sizeof(itemName), stdin);
for (int i = 0; itemName[i] != '\\0'; i++) {
if (itemName[i] == '\\n') {
itemName[i] = '\\0';
break;
}
}
if (strcmp(itemName, "done") == 0 || strcmp(itemName, "Done") == 0) {
break; // Exit loop
}
printf("Enter Quantity for %s: ", itemName);
scanf("%d", &qty);
printf("Enter Price per unit for %s: ", itemName);
scanf("%f", &price);
while (getchar() != '\\n'); // Clear input buffer
itemTotal = qty * price;
subtotal += itemTotal;
printf("%-15s %-5d %-10.2f %-10.2f\\n", itemName, qty, price, itemTotal);
printf("Add another item? (y/n): ");
scanf(" %c", &addMore);
while (getchar() != '\\n'); // Clear input buffer
}
// Step 5: Calculate tax, discount, and total payable
taxAmount = subtotal * taxRate;
discountAmount = subtotal * discountRate; // Discount applied before tax is common, but here after subtotal
totalPayable = subtotal + taxAmount - discountAmount;
// Step 6: Print final bill with tax and discount
printf("----------------------------------------\\n");
printf("%-32s %-10.2f\\n", "Subtotal:", subtotal);
printf("%-32s %-10.2f\\n", "Tax (%.0f%%):", taxRate * 100, taxAmount);
printf("%-32s %-10.2f\\n", "Discount (%.0f%%):", discountRate * 100, discountAmount);
printf("----------------------------------------\\n");
printf("%-32s %-10.2f\\n", "Total Payable:", totalPayable);
printf("----------------------------------------\\n");
return 0;
}
Sample Output:
Enter Customer Name: Alice Wonderland
--- Bill Statement ---
Customer Name: Alice Wonderland
----------------------------------------
Item Qty Price Total
----------------------------------------
Enter Item Name (or type 'done' to finish): Pen
Enter Quantity for Pen: 5
Enter Price per unit for Pen: 2.50
Pen 5 2.50 12.50
Add another item? (y/n): y
Enter Item Name (or type 'done' to finish): Notebook
Enter Quantity for Notebook: 2
Enter Price per unit for Notebook: 8.00
Notebook 2 8.00 16.00
Add another item? (y/n): y
Enter Item Name (or type 'done' to finish): Eraser
Enter Quantity for Eraser: 3
Enter Price per unit for Eraser: 1.00
Eraser 3 1.00 3.00
Add another item? (y/n): n
----------------------------------------
Subtotal: 31.50
Tax (10%): 3.15
Discount (5%): 1.58
----------------------------------------
Total Payable: 33.07
----------------------------------------
Stepwise Explanation:
- Variable Declaration: New variables
taxRate,discountRate,taxAmount,discountAmount, andtotalPayableare introduced. - Customer Name & Item Loop: Steps 2, 3, and 4 are identical to Approach 2, focusing on getting customer and item details and calculating the
subtotal. - Tax, Discount, and Total Calculation: After the item input loop,
taxAmountis calculated by multiplyingsubtotalbytaxRate.discountAmountis calculated similarly. Finally,totalPayableis found by adding thetaxAmountand subtracting thediscountAmountfrom thesubtotal. - Final Bill Output: The program prints the
subtotal, followed by thetaxAmount,discountAmount, and thetotalPayable, clearly indicating the percentages used for tax and discount.
Conclusion
Creating a bill statement program in C demonstrates fundamental programming concepts like input/output handling, arithmetic operations, and conditional logic. From a basic fixed-item bill to a more dynamic and comprehensive version with tax and discount calculations, C provides the tools necessary to build efficient console-based applications for various business needs.
Summary
- Bill statement programs automate the calculation of itemized purchases and total amounts.
- Basic C features like
printf(),scanf(), and variable declarations are crucial. -
fgets()and input buffer clearing (while (getchar() != '\n');) are important for robust input handling, especially when mixingscanf()andfgets(). - Using
whileloops enables dynamic item entry, making the program more flexible. - Including tax and discount calculations makes the bill statement more realistic for real-world applications.