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