C Online Compiler
Example: Rainfall Statistics (Sentinel Value) in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Rainfall Statistics (Sentinel Value) #include <stdio.h> #include <float.h> // For FLT_MAX and FLT_MIN int main() { // Step 1: Declare variables for sum, count, min, max, and current input. float currentRate; float sum = 0.0f; int count = 0; float lowestRate = FLT_MAX; // Initialize with largest possible float value float highestRate = FLT_MIN; // Initialize with smallest possible float value // Step 2: Prompt for input with instructions for sentinel value. printf("Enter rainfall rates (mm/hour). Enter -1 to stop.\n"); // Step 3: Loop to get rainfall rates until the sentinel is entered. while (1) { // Infinite loop, will break manually printf("Enter rate: "); scanf("%f", ¤tRate); if (currentRate == -1) { break; // Exit loop if sentinel value is entered } // Validate positive rain rate, or allow 0 for no rain if (currentRate < 0) { printf("Rainfall rates cannot be negative. Please enter a valid rate or -1 to stop.\n"); continue; // Skip to next iteration without processing invalid input } // Step 4: Update sum, count, min, and max. sum += currentRate; count++; if (currentRate < lowestRate) { lowestRate = currentRate; } if (currentRate > highestRate) { highestRate = currentRate; } } // Step 5: Check if any valid rates were entered before calculating average. if (count > 0) { float averageRate = sum / count; printf("\n--- Rainfall Statistics ---\n"); printf("Average Rainfall Rate: %.2f mm/hour\n", averageRate); printf("Lowest Rainfall Rate: %.2f mm/hour\n", lowestRate); printf("Highest Rainfall Rate: %.2f mm/hour\n", highestRate); } else { printf("\nNo rainfall rates were entered.\n"); } return 0; }
Output
Clear
ADVERTISEMENTS