Program 11
Develop a program using
pointers to compute the
sum, mean and standard deviation of all elements stored in
an array of N real numbers. This program demonstrates advanced pointer arithmetic,
statistical calculations, and memory management techniques for numerical data analysis.
Algorithm
- Input Array Size: Read N (number of elements) from user
- Declare Array: Create array of N double elements
- Initialize Pointer: Set pointer p to point to array base address
- Input Elements: Use pointer arithmetic to read N real numbers
- Calculate Sum: Traverse array using pointer and accumulate sum
- Compute Mean: Divide total sum by number of elements
- Calculate Variance: Find sum of squared differences from mean
- Compute Standard Deviation: Take square root of variance
- Display Results: Print sum, mean, and standard deviation
Flowchart
START
→
Input N
→
Initialize Pointer
→
Read Array Elements
→
Calculate Sum
→
Compute Mean
→
Calculate SD
→
Display Results
→
STOP
Code
#include <stdio.h>
#include <math.h>
int main() {
int n, i;
double sum = 0, mean, sd = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
double arr[n];
double *p = arr; // pointer to array
printf("Enter %d real numbers:\n", n);
for (i = 0; i < n; i++) {
scanf("%lf", (p + i)); // using pointer
sum += *(p + i);
}
// Calculate mean
mean = sum / n;
// Calculate standard deviation
for (i = 0; i < n; i++) {
sd += pow(*(p + i) - mean, 2);
}
sd = sqrt(sd / n);
// Output
printf("\nSum = %.2lf\n", sum);
printf("Mean = %.2lf\n", mean);
printf("Standard Deviation = %.2lf\n", sd);
return 0;
}