lucproblem014.c (3077B)
1 /* 2 * Author : Amit Dutta <amitdutta4255@gmail.com> 3 * Date : 12 Dec 2025 4 * Repo : https://github.com/notamitgamer/bsc 5 * License : MIT License (See the LICENSE file for details) 6 */ 7 8 /* Write a function that receives integers and returns the sum, average 9 and standard deviation of these numbers. Call this function from main() 10 and print the result in main() */ 11 /* Let Us C, Chap - 9, Page 158, Problem 9.1 */ 12 13 #include <stdio.h> 14 #include <math.h> 15 16 // Function prototype: Using pointers for 'call by reference' to return 3 values. 17 void stats(double *, double *, double *); 18 19 int main() 20 { 21 double sum, average, standardDeviation; 22 // Passing addresses of variables to receive results from the function. 23 stats(&sum, &average, &standardDeviation); 24 25 printf("\n--- Stats ---" 26 "\nSum: %g" 27 "\nAverage: %g" 28 "\nStandard Deviation: %g", 29 sum, average, standardDeviation); 30 return 0; 31 } 32 33 // Function to calculate statistics on user-provided numbers. 34 void stats(double *sum, double *average, double *standardDeviation) 35 { 36 int n; 37 // Input Validation Loop for N 38 do 39 { 40 printf("How many numbers you want to give input: "); 41 42 if (scanf("%d", &n) == 1) 43 { 44 break; 45 } 46 else 47 { 48 printf("\nPlease enter a valid number.\n"); 49 // Clearing input buffer to handle invalid input 50 while (getchar() != '\n' && !feof(stdin)) 51 ; 52 } 53 } while (1); 54 55 // Variable-Length Array (VLA) to store the input numbers. 56 double inputNumber[n]; 57 int i = 0; 58 59 printf("\n--- Enter Numbers ---\n"); 60 61 // Input Loop for numbers 62 while (i < n) 63 { 64 printf("Enter number %d: ", i + 1); 65 66 if (scanf("%lf", &inputNumber[i]) == 1) 67 { 68 // Clearing input buffer after successful read 69 while (getchar() != '\n') 70 ; 71 i++; 72 } 73 else 74 { 75 printf("Invalid input. Only integers are allowed. Please try again.\n"); 76 // Clearing input buffer to handle invalid input 77 while (getchar() != '\n' && !feof(stdin)) 78 ; 79 } 80 } 81 82 // 1. Sum Calculation 83 double tempSum = 0; 84 for (i = 0; i < n; i++) 85 tempSum += inputNumber[i]; 86 87 // 2. Average (Mean) calculation 88 double tempAverage = tempSum / n; 89 90 // 3. Standard Deviation (Sample SD formula used) 91 double tempStandardDeviation = 0.0; 92 93 // Preventing division by zero if n is 1. SD is 0 for a single number. 94 if (n > 1) 95 { 96 double tempSumation = 0; 97 // calculating the sum of squared differences from the mean 98 for (i = 0; i < n; i++) 99 tempSumation += pow((inputNumber[i] - tempAverage), 2.0); 100 101 // Calculating sample standard deviation 102 tempStandardDeviation = sqrt(tempSumation / (n - 1)); 103 } 104 105 // Assigning final values back to the variables in main(). 106 *sum = tempSum; 107 *average = tempAverage; 108 *standardDeviation = tempStandardDeviation; 109 }