Using procedures and functions, write a C/C++ program that prompts the user to e
ID: 3663341 • Letter: U
Question
Using procedures and functions, write a C/C++ program that prompts the user to enter a value n(5 < n 20). If the value of n is out of range, prompt the user again for n. Next prompt the user to enter those n real numbered scores into an array. Since you do not know how large n is, dynamically allocate your array using the malloc() function. Your program is compute the mean, median, mode, and sample standard deviation of your data set and output the results. You must use procedures and functions for this problem. Name this program csf hw1 q2.c. Include sample output in your solution.
Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main() {
float *x, mean = 0, median, sd, var;
int n, i, j, temp;
printf("Enter the no of entries:");
scanf("%d", &n);
x = (float *)malloc(sizeof (float) * n);
/* get n inputs from user */
printf("Enter your inputs: ");
for (i = 0; i < n; i++)
{
scanf("%f", &x[i]);
if(x[i]>5 && x[i]<=20)
{
/* calculate the mean */
for (i = 0; i < n; i++)
mean = mean + x[i];
mean = mean / n;
/* calculate the variance*/
for (i = 0; i < n; i++)
var = var + pow((x[i] - mean) , 2);
var = var / n;
/* square root of variance is SD */
sd = sqrt(var);
/* sort the given inputs to find median */
for (i = 0; i < n - 1; i++)
for (j = i; j < n; j++) {
if (x[i] > x[j]) {
temp = x[i];
x[i] = x[j];
x[j] = temp;
}
}
/* calculate the median */
if ((n + 1) % 2 == 0) {
median = x[((n + 1) / 2) - 1];
} else {
median = (x[((n + 1) / 2) - 1] + x[((n + 2) / 2) - 1]) / 2;
}
}
else
printf(" Values are not in range ");
}
/* print the outputs */
printf("Standard deviation: %f ", sd);
printf("Variance: %f ", var);
printf("Mean : %f ", mean);
printf("Median: %f ", median);
return 0;
}
Sample Output:
Enter the no of entries: 5
Enter your inputs: 6 7 8 9 10
Standard deviation: 1.414
Variance : 2.0
Mean : 8
Median : 8
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.