C Online Compiler
Example: Shipping Charge Calculator with Discounts in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Shipping Charge Calculator with Discounts #include <stdio.h> int main() { // Step 1: Declare variables for weight, base rate, total cost, and discount rate. float weight_kg; float base_rate_per_kg = 5.00; // Example base rate: $5.00 per kg float total_cost; float discount_rate = 0.0; // Initialize discount rate to 0% // Step 2: Prompt user for package weight and read input. printf("Enter the package weight in kilograms: "); scanf("%f", &weight_kg); // Step 3: Calculate the initial total cost before discount. total_cost = weight_kg * base_rate_per_kg; // Step 4: Apply discounts based on weight using if-else if statements. if (weight_kg <= 5.0) { discount_rate = 0.0; // No discount for 5 kg or less } else if (weight_kg > 5.0 && weight_kg <= 10.0) { discount_rate = 0.10; // 10% discount for >5 kg to 10 kg } else if (weight_kg > 10.0 && weight_kg <= 20.0) { discount_rate = 0.15; // 15% discount for >10 kg to 20 kg } else { // weight_kg > 20.0 discount_rate = 0.20; // 20% discount for >20 kg } // Step 5: Calculate the final cost after applying the discount. float discount_amount = total_cost * discount_rate; float final_cost = total_cost - discount_amount; // Step 6: Display the results to the user. printf("\n--- Shipping Details ---\n"); printf("Package Weight: %.2f kg\n", weight_kg); printf("Base Rate: $%.2f per kg\n", base_rate_per_kg); printf("Initial Cost: $%.2f\n", total_cost); printf("Discount Applied: %.0f%%\n", discount_rate * 100); printf("Discount Amount: $%.2f\n", discount_amount); printf("Final Shipping Cost: $%.2f\n", final_cost); return 0; }
Output
Clear
ADVERTISEMENTS