C Program For Purchased Bakery Items And To Find Their Average
Calculating the average price of purchased bakery items is a common task, whether for personal budgeting or small business management. This process involves collecting the prices of individual items and then computing their mean value.
In this article, you will learn how to write a C program that prompts the user for the number of bakery items, takes their individual prices as input, and then calculates and displays the total cost and the average price.
Problem Statement
Many situations require calculating the average cost of multiple items. For instance, a small bakery owner might want to know the average cost of ingredients for a batch of pastries, or an individual might track their weekly spending on baked goods. The challenge is to efficiently collect a variable number of prices and perform accurate arithmetic to find their sum and average. This can provide valuable insights into spending patterns or ingredient costs.
Example
Here's an example of how the program will interact with the user and display the results:
Enter the number of bakery items purchased: 3
Enter price for item 1: 2.50
Enter price for item 2: 1.75
Enter price for item 3: 3.00
Total cost of bakery items: $7.25
Average price per item: $2.42
Background & Knowledge Prerequisites
To understand and implement this program, readers should have a basic understanding of:
- C Data Types:
intfor whole numbers andfloatordoublefor decimal numbers. - Input/Output Operations: Using
scanf()to read user input andprintf()to display output. - Loops: Specifically, the
forloop to iterate a fixed number of times. - Variables: Declaring and assigning values to variables.
- Basic Arithmetic Operators: Addition (
+) and division (/).
Use Cases or Case Studies
Calculating averages is a fundamental operation with wide applicability. Here are a few practical examples for this specific scenario:
- Personal Budgeting: Track the average cost of your daily coffee and pastry to understand your spending habits.
- Small Business Inventory: A cafe owner can calculate the average cost of different types of bread purchased from a supplier to inform pricing strategies.
- Educational Tool: Students learning C programming can use this as a simple, practical exercise to grasp loops, input, and basic calculations.
- Event Planning: If catering a small event with assorted baked goods, calculate the average cost per guest for the bakery portion.
- Comparative Shopping: Compare the average price of bakery items across different stores to find the most economical option.
Solution Approaches
For calculating the average of a series of numbers, the most straightforward approach involves summing all the numbers and then dividing by their count.
Approach: Calculating Average Price of Bakery Items
This approach uses a for loop to collect prices one by one, accumulates their sum, and then computes the average after all inputs are received.
// Calculate Average Price of Bakery Items
#include <stdio.h> // Required for input/output functions like printf and scanf
int main() {
// Step 1: Declare necessary variables
int numberOfItems; // To store the count of bakery items
float itemPrice; // To store the price of each individual item
float totalCost = 0.0; // To accumulate the sum of all item prices, initialized to 0
float averagePrice; // To store the calculated average price
// Step 2: Prompt the user to enter the number of bakery items
printf("Enter the number of bakery items purchased: ");
scanf("%d", &numberOfItems); // Read the integer value into numberOfItems
// Step 3: Use a loop to get the price for each item
// The loop will run 'numberOfItems' times
for (int i = 1; i <= numberOfItems; i++) {
printf("Enter price for item %d: ", i); // Prompt for the price of the current item
scanf("%f", &itemPrice); // Read the float value into itemPrice
totalCost += itemPrice; // Add the current item's price to totalCost
}
// Step 4: Calculate the average price
// Check to prevent division by zero if no items were entered
if (numberOfItems > 0) {
averagePrice = totalCost / numberOfItems;
// Step 5: Display the total cost and average price
printf("\\nTotal cost of bakery items: $%.2f\\n", totalCost); // .2f for 2 decimal places
printf("Average price per item: $%.2f\\n", averagePrice);
} else {
printf("\\nNo items were entered, so average cannot be calculated.\\n");
}
return 0; // Indicate successful execution of the program
}
Sample Output
Enter the number of bakery items purchased: 4
Enter price for item 1: 1.50
Enter price for item 2: 2.25
Enter price for item 3: 1.75
Enter price for item 4: 3.00
Total cost of bakery items: $8.50
Average price per item: $2.13
Stepwise Explanation
- Include Header: The
#includeline includes the standard input/output library, providing functions likeprintffor printing to the console andscanffor reading user input. - Declare Variables:
-
numberOfItems(anint) stores how many items the user purchased. -
itemPrice(afloat) temporarily holds the price of each item as it's entered. -
totalCost(afloat) accumulates the sum of all item prices. It's initialized to0.0. -
averagePrice(afloat) stores the final calculated average.
- Get Item Count: The program prompts the user to enter the total number of bakery items and reads this integer using
scanf("%d", &numberOfItems). - Loop for Prices: A
forloop iterates from1up tonumberOfItems. In each iteration:
- It prompts the user to enter the price for the current item (
item %d). - It reads the floating-point price using
scanf("%f", &itemPrice). - It adds the
itemPricetototalCost.
- Calculate Average: After the loop finishes, the program checks if
numberOfItemsis greater than 0 to avoid division by zero. If valid,averagePriceis calculated by dividingtotalCostbynumberOfItems. - Display Results: Finally,
printfis used to display both thetotalCostandaveragePrice, formatted to two decimal places using%.2f. - Return 0: The
return 0;statement indicates that the program executed successfully.
Conclusion
This C program provides a simple yet effective solution for calculating the total and average price of a variable number of bakery items. It demonstrates fundamental C programming concepts such as variable declaration, input/output operations, and loop structures. This basic framework can be extended for more complex inventory or budgeting applications.
Summary
- Initialize Variables: Set up
intfor item count andfloatfor prices and totals. - Get Item Count: Prompt the user for the total number of items to process.
- Loop for Prices: Use a
forloop to repeatedly ask for each item's price and accumulate thetotalCost. - Calculate Average: Divide
totalCostby thenumberOfItemsto find theaveragePrice, ensuring to handle cases with zero items. - Display Results: Print the calculated
totalCostandaveragePricein a user-friendly format.