C Online Compiler
Example: Enhanced Bill with Tax and Discount in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// 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; }
Output
Clear
ADVERTISEMENTS