Loading your workspace…
Loading your workspace…
Use pointers to walk an array of n real numbers and compute their sum, mean and standard deviation.
#include <stdio.h>
#include <math.h>
#define MAX 100
void statistics(const double *arr, int n, double *sum, double *mean, double *std_dev) {
const double *p;
double total = 0.0;
double squared = 0.0;
double diff;
for (p = arr; p < arr + n; p++) {
total += *p;
}
*sum = total;
*mean = total / n;
for (p = arr; p < arr + n; p++) {
diff = *p - *mean;
squared += diff * diff;
}
*std_dev = sqrt(squared / n);
}
int main(void) {
double arr[MAX];
double sum, mean, std_dev;
int n, i;
printf("Enter number of values (1-%d):\n", MAX);
if (scanf("%d", &n) != 1 || n < 1 || n > MAX) {
printf("Error: invalid count\n");
return 1;
}
printf("Enter %d real numbers:\n", n);
for (i = 0; i < n; i++) {
scanf("%lf", &arr[i]);
}
statistics(arr, n, &sum, &mean, &std_dev);
printf("Sum : %.2f\n", sum);
printf("Mean : %.2f\n", mean);
printf("Standard deviation: %.2f\n", std_dev);
return 0;
}
Input
8
2 4 4 4 5 5 7 9Output
Enter number of values (1-100):
Enter 8 real numbers:
Sum : 40.00
Mean : 5.00
Standard deviation: 2.00Input
1
3.5Output
Enter number of values (1-100):
Enter 1 real numbers:
Sum : 3.50
Mean : 3.50
Standard deviation: 0.00The statistics function never uses array indexing; p starts at arr and advances one element at a time until it reaches arr + n. Since p is a pointer to double, p++ moves to the next element automatically.
The standard deviation here is the population form, dividing by n. A sample standard deviation would divide by n - 1 instead, which the lab statement does not ask for.
Edit the program and press Run. It is free and needs no sign-in.
Copy a sample and paste it into the STDIN box in the editor before you press Run.
8 2 4 4 4 5 5 7 9
Expected output
Enter number of values (1-100): Enter 8 real numbers: Sum : 40.00 Mean : 5.00 Standard deviation: 2.00
1 3.5
Expected output
Enter number of values (1-100): Enter 1 real numbers: Sum : 3.50 Mean : 3.50 Standard deviation: 0.00
It advances p by sizeof(double) bytes, so it points to the next element of the array.
A C function returns only one value, so pointers let it send back three results through the caller's variables.
The population form divides by n; the sample form divides by n - 1 to correct for estimating the mean from a sample.
sqrt is in the maths library, which must be linked explicitly on many systems.
The function only reads the values, so const documents this and protects the data.
Back to all VTU BPOPS103 lab programs.