C Program to Calculate Average Value of Two Items
Learning C? This program clearly demonstrates floating-point input, arithmetic and averages. Calculate the average value of two items from their weights and quantities, solidifying scanf() and printf() use in a practical context.
Heads Up: This program uses simple averaging, ignoring complex statistical weighting.
#include <stdio.h> // Essential for console input (scanf) and output (printf) int main() { float weight1, weight2; // Weights of the two items float quantity1, quantity2; // Number of units for each item float totalWeight, totalQuantity, average; // Variables for calculations and result // Get input for first item printf("Enter weight and number of purchases for item 1: "); scanf("%f %f", &weight1, &quantity1); // Get input for second item printf("Enter weight and number of purchases for item 2: "); scanf("%f %f", &weight2, &quantity2); // Calculate totals totalWeight = (weight1 * quantity1) + (weight2 * quantity2); totalQuantity = quantity1 + quantity2; // Calculate average average = totalWeight / totalQuantity; // Display result printf("Average value per item = %.2f\n", average); return 0; // Program finished successfully } Sample Output: Enter weight and number of purchases for item 1: 5.5 2 Enter weight and number of purchases for item 2: 3.0 3 Average value per item = 3.90
Program Breakdown: Essential C Concepts
This C program processes numerical input and performs calculations using floating-point variables for decimal accuracy.
Input/Output (scanf, printf): Your tools for getting user data (using %f for decimals) and presenting results.
Calculation Logic: Determines totalWeight (each item's weight * quantity summed) and totalQuantity. average is then totalWeight / totalQuantity.
Formatting (%.2f): Ensures the final average displays neatly, rounded to two decimal places.
This demonstrates core C skills: input, precise calculation, and clear output in one clean solution.
Conclusion
You've successfully coded a practical C program for calculating averages! This exercise is crucial for understanding floating-point numbers, user input, and arithmetic operations in C. Challenge yourself: add more items, or try different data types for greater precision!