Programming in C Language. Please refer to images for details about assignment.
ID: 3906077 • Letter: P
Question
Programming in C Language. Please refer to images for details about assignment. Also attached the text file that program gets numbers from.
Explanation / Answer
Given below is the code for the question.
Please do rate the answer if it was helpful. Thank you
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
double sum(char *s);
void stats(char *s, double *meanPtr, double *varPtr);
void printDigitCounts(char *s);
int main()
{
char s[4][100] = {"12, 34, 56, 78",
"82.16, 41.296",
"2, -3, 5, -7, 11, -13, 17, -19",
"9.00009, 90.0009, 900.009, 9000.09, 90000.9"};
int i;
double mean, variance;
for(i = 0; i < 4; i++)
{
printf("Calculating for string %s ", s[i]);
printf("Sum: %.6f ", sum(s[i]));
stats(s[i], &mean, &variance);
printf("Mean: %.6f ", mean);
printf("Variance: %.6f ", variance);
printDigitCounts(s[i]);
printf("--------------------- ");
}
}
double sum(char *str)
{
char s[100];
char *token;
double total = 0;
strcpy(s, str);
token = strtok(s, ",");
while(token != NULL)
{
total = total + atof(token);
token = strtok(NULL, ",");
}
return total;
}
void stats(char *str, double *meanPtr, double *varPtr)
{
int n = 0;
char *token;
double total = 0;
double mean;
double var = 0, x, diff;
char s[100];
strcpy(s, str);
token = strtok(s, ",");
while(token != NULL)
{
total = total + atof(token);
token = strtok(NULL, ",");
n++;
}
mean = total / n;
*meanPtr = mean;
strcpy(s, str);
token = strtok(s, ",");
while(token != NULL)
{
x = atof(token);
//printf("%f ", x);
diff = x - mean;
var = diff * diff;
token = strtok(NULL, ",");
}
var = var / (n-1);
var = sqrt(var);
*varPtr = var;
}
void printDigitCounts(char *s)
{
int counts[10] = {0};
int i;
char ch;
int digit;
for(i = 0; s[i] != ''; i++)
{
ch = s[i];
if(ch >= '0' && ch <= '9')
{
digit = ch - '0'; //convert from char to digit but subtracting ascii
counts[digit]++; //increment counter for corrsponding digit
}
}
printf("%d", counts[0]);
for(i = 1; i < 10; i++)
printf(", %d", counts[i]);
printf(" ");
}
output
====
Calculating for string 12, 34, 56, 78
Sum: 180.000000
Mean: 45.000000
Variance: 19.052559
0, 1, 1, 1, 1, 1, 1, 1, 1, 0
---------------------
Calculating for string 82.16, 41.296
Sum: 123.456000
Mean: 61.728000
Variance: 20.432000
0, 2, 2, 0, 1, 0, 2, 0, 1, 1
---------------------
Calculating for string 2, -3, 5, -7, 11, -13, 17, -19
Sum: -7.000000
Mean: -0.875000
Variance: 6.850606
0, 5, 1, 2, 0, 1, 0, 2, 0, 1
---------------------
Calculating for string 9.00009, 90.0009, 900.009, 9000.09, 90000.9
Sum: 99999.999990
Mean: 19999.999998
Variance: 35000.450001
20, 0, 0, 0, 0, 0, 0, 0, 0, 10
---------------------
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.