-
while loops with arrays
Code:
#include <stdio.h>
#include <math.h>
float average(int sum, int array_size);
float std(int sum, int array_size);
int main(void)
{
int a[3] = {0};
int b[3] = {0};
int sum = 0;
int i = 0;
float av;
float st;
float av2;
float st2;
printf("Enter three numbers\n");
while (scanf("%d", &a[i]) !=EOF)
{
sum += a[i++];
if (i == 3)
break;
}
av = average(sum, i);
st = std(sum, i);
printf("\nThe average of the numbers you entered is %.2f\n",av);
printf("\nThe standard deviation is %.2f\n",st);
printf("\nEnter three more numbers\n");
while (scanf("%d", &b[i]) !=EOF)
{
sum += b[i++];
if (i == 3)
break;
}
av2 = average(sum, i);
st2 = std(sum, i);
printf("\nThe average of the numbers you entered is %.2f\n",av2);
printf("\nThe standard deviation is %.2f\n",st2);
return 0;
}
float average(int sum, int array_size)
{
return (float) sum/array_size;
}
float std(int sum, int array_size)
{
return (float) sqrt((pow(sum,2) + pow(sum/3,2))/array_size - 1);
}
Why isn't the second while loop working properly?
-
Hello, volk
Before the line:
printf("\nEnter three more numbers\n");
you have omitted to re-initialise variables i and sum to zero...
Cheers from MrB :)
-