How to compute min, max, average from an array? [closed] - c

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
This is the original question asked:
1.The user will input up to 20 numbers, and these numbers will be stored in an array. Write functions will take as input and return the minimum, the maximum, and the average. Use the functions to compute the min, max, and average of the array.
Here is what I have but I dont know why it is not working, any suggestions?
#include <stdio.h>
void arrmin(int a[],int num_elements);
void arrmax(int a[], int num_elements);
void arraver(int a[],int num_elements);
int main(void)
{
int a[20],c,min,max;
float avg;
printf("Enter 20 numbers of elements in array\n");
for (c = 0; c < 20; c++)
scanf("%d", &a[c]);
min=max=a[0];
arrmax(a,a[20]);
printf("Maximum value is %d\n", max);
arrmin(a,a[20]);
printf("Minimum value is %d\n", a[20]);
arraver(a,a[20]);
printf("Average value is %f\n", a[20]);
getch();
}
void arrmax(int a[], int num_elements)
{
int i, max;
for (i=0; i<num_elements; i++)
{
if (a[i]>max)
{
max=a[i];
}
}
return(max);
}
void arrmin(int a[], int num_elements)
{
int i, min;
for (i=0; i<num_elements; i++)
{
if (a[i]<min)
{
min=a[i];
}
}
return(min);
}
void arraver(int a[], int num_elements)
{ int sum,i;
float avg;
sum=0;
avg=0;
for (i=0; i<num_elements;i++)
{
sum=sum+a[i];
avg=(float)sum/(i+1);
}
return(avg);
}

Your logic looks pretty good, but there are a few small issues. The fixed code is given at the bottom of the answer.
Issues:
Pass 20 to the second argument of arrmax, arrmin, and arraver
arrmax(a,a[20]); becomes arrmax(a, 20).
You probably want the arr... functions to return int or float rather than void
void arrmax(...) becomes int arrmax(...)
void arraver(...) becomes float arraver(...)
Be sure to actually use the values returned by your functions
arrmax(a,20); becomes max = arrmax(a, 20);, etc.
Be sure to initialize max and min variables in their respective functions.
max = a[0];
min = a[0];
now we can iterate from 1 to 19 instead of 0 to 19
The min and aver printers should print min and aver rather than a[20].
printf("Min is %d\n", a[20]); becomes printf("Min is %d\n", min);
printf("Average is %f\n", a[20]); becomes printf("Average is %f\n", aver);
Fixed code:
#include <stdio.h>
int arrmin(int a[],int num_elements);
int arrmax(int a[], int num_elements);
float arraver(int a[],int num_elements);
int main(void)
{
int a[20],c,min,max;
float avg;
printf("Enter 20 numbers of elements in array\n");
for (c = 0; c < 20; c++)
scanf("%d", &a[c]);
max = arrmax(a,20);
printf("Maximum value is %d\n", max);
min = arrmin(a,20);
printf("Minimum value is %d\n", min);
avg = arraver(a,20);
printf("Average value is %f\n", avg);
getch();
}
int arrmax(int a[], int num_elements)
{
int i, max;
max = a[0];
for (i=1; i<num_elements; i++)
{
if (a[i]>max)
{
max=a[i];
}
}
return(max);
}
int arrmin(int a[], int num_elements)
{
int i, min;
min = a[0];
for (i=1; i<num_elements; i++)
{
if (a[i]<min)
{
min=a[i];
}
}
return(min);
}
float arraver(int a[], int num_elements)
{
int sum,i;
float avg;
sum=0;
avg=0;
for (i=0; i<num_elements;i++)
{
sum=sum+a[i];
avg=(float)sum/(i+1);
}
return(avg);
}

Related

I'm getting values but not as it should be

Problem: Write a program in C to get the largest element, smallest element, sum of all elements and multiplication of all elements of an array using the functions. (Make four different functions for four calculations and call them for one array given by user).
I think I'm getting error because of i and n.
I'm a beginner and I can't explain every thing line by line. Code:
#include <stdio.h>
// defined Max function int Max(int arr[], int);
// defined Min function int Min(int arr[], int);
// defined Sum function int Sum(int arr[], int);
// defined Mul function int Mul(int arr[], int);
int main() {
int i, n, arr[100];
printf("Input the number of elements to be stored in the array : ");
scanf("%d",&n);
printf("Input %d elements in the array: \n",n);
for (i=0; i<n; i++)
{
printf("element - %d : ",i);
scanf("%d", &arr[i]);
}
n = Max( arr, n);
printf("The largest element in the array is : %d", n);
n = Min( arr, n);
printf("\nThe smallest element in the array is : %d", n);
n = Sum( arr, n);
printf("\nThe sum of all the elements in the array is : %d", n);
n = Mul( arr, n);
printf("\nThe multiplication of all the elements in the array is : %d", n);
return 0;
}
int Max(int arr[], int n)
{
int max = arr[0];
for (int i=0; i<n; i++)
{
if (max<arr[i])
max=arr[i];
}
return max;
}
int Min(int arr[], int n)
{
int min = arr[0];
for (int i=0; i<n; i++)
{
if (min>arr[i])
min=arr[i];
}
return min;
}
int Sum(int arr[], int n)
{
int sum = arr[0];
for (int i=0; i<n; i++)
{
sum += arr[i];
}
return sum;
}
int Mul(int arr[], int n)
{
int mul = arr[0];
for (int i=0; i<n; i++)
{
mul *= arr[i];
}
return mul;
}
As suggested in one comment, your for should start from 1, otherwise you use the element 0 twice, and thus producing always a wrong result. Here is how the for related to Mul function should appear, just apply the same for other ones:
int mul = arr[0];
for(int i=1; i<n; i++)
{
mul *= arr[i];
}
return mul;
In addition to the above, there is another bug in your code, which is the way you use the variable n.
As far as I see, that variable stores the number of elements of the array. It is a valid input for all the sub-routines, but you cannot re-assign it with the result of each of them. In this way, it's like you are invoking the sub-routines always with a different array size, and of course you get unexpected results.
So, one possible solution would be to define and use another local variable which holds the results from each sub-routines.
To help you with your issue, I fixed your code, it works fine now. There you go:
#include <stdio.h>
// defined Max function int Max(int arr[], int);
// defined Min function int Min(int arr[], int);
// defined Sum function int Sum(int arr[], int);
// defined Mul function int Mul(int arr[], int);
int main() {
int i, n, op_res, arr[100];
printf("Input the number of elements to be stored in the array : ");
scanf("%d",&n);
printf("Input %d elements in the array: \n",n);
for (i=0; i<n; i++)
{
printf("element - %d : ",i);
scanf("%d", &arr[i]);
}
op_res = Max( arr, n);
printf("The largest element in the array is : %d", op_res);
op_res = Min( arr, n);
printf("\nThe smallest element in the array is : %d", op_res);
op_res = Sum( arr, n);
printf("\nThe sum of all the elements in the array is : %d", op_res);
op_res = Mul( arr, n);
printf("\nThe multiplication of all the elements in the array is : %d", op_res);
return 0;
}
int Max(int arr[], int n)
{
int max = arr[0];
for (int i=0; i<n; i++)
{
if (max<arr[i])
max=arr[i];
}
return max;
}
int Min(int arr[], int n)
{
int min = arr[0];
for (int i=0; i<n; i++)
{
if (min>arr[i])
min=arr[i];
}
return min;
}
int Sum(int arr[], int n)
{
int sum = arr[0];
for (int i=1; i<n; i++)
{
sum += arr[i];
}
return sum;
}
int Mul(int arr[], int n)
{
int mul = arr[0];
for (int i=1; i<n; i++)
{
mul *= arr[i];
}
return mul;
}

How to find the closest elements of average in C?

Hi, how can I find the closest number of average in this array?
Idk how to do this.
#include<stdio.h>
#include<stdlib.h>
int arraysum();
int main()
{
int n, A[100], i, b, sum;
float average;
printf("Enter number of elements in array: ");
scanf("%d", &n);
printf("\nEnter %d numbers: ", n);
for(i=0; i<n; i++)
scanf("%d", &A[i]);
printf("Numbers of this array: ");
for(i=0; i<n; i++)
printf("%d ", A[i]);
average=arraysum(A, sum, i, n)/n;
printf("\nAverage is: %.2f", average);
}
int arraysum(int A[], int sum, int i, int n)
{
sum=0;
for(i=0; i<n; i++)
sum+=A[i];
return sum;
}
Thanks in advance, guys!
:D
After finding the average, iterate looking for closest.
// Pseudo code
average=arraysum(A, sum, i, n)/n;
best = element 0
for (each element in the array [1...n-1])
if (|A[i] - average| < |A[best] - average|)
best = i
To cope with an average than is not exactly an integer and not use unnecessary floating point math ...
long long scaled_average = arraysum(A, sum, i, n);
best = element 0
for (each element in the array [1...n-1])
if (|n*A[i] - scaled_average| < |n*A[best] - scaled_average|)
best = i
Consider using long long for sum to avoid overflow.
Code simplification: no need to pass in sum.
long long arraysum(int A[], int i, int n) {
long long sum = 0;
for(i=0; i<n; i++)
sum+=A[i];
return sum;
}
First suggestion is to move the declaration of A[100]; from here
int n, A[100], i, b, sum;
To just after the scanf() statement, to create a VLA:
int n, i, b, sum;
...
printf("Enter number of elements in array: ");
scanf("%d", &n);
int A[n];
for(i=0; i<n; i++)
scanf("%d", &A[i]);
...creating an array just the right size for the need.
Once the array is populated, loop through it and use comparison operators to find the closest to the difference of array values and average. (pseudo code: fabs(a[i]-ave) < fabs(a[i+1]-ave)) tracking the array index of the array values closest.
Example:
average = arraysum(A, sum, i, n)/(n*(1.0));//divide by floating point
int closestIndex;
findClosest(int A, 100, average, &closestIndex);
printf("Index of value closest to %f is %d\nClosest value is: %d\n",
average, closestIndex, A[closestIndex]);
Where findClosest() is defined:
void findClosest(int A[], size_t size, double ave int *index)
{
int smallestIndex;
for(int i=0;i<size-1;i++)
{
smallestIndex = fabs((double)A[i]-ave) < fabs((double)A[i+1]-ave) ? i : i + 1;
}
*index = smallestIndex
}

Why `pow(sum,1/2)` is not giving me the same result as `sqrt(sum))`?

In the code at the end, there is a function at the bottom called general_norm that uses the following print() functions:
printf(" %f",sqrt(sum));
printf(" %f",pow(sum,1/2));
While sqrt(sum)) is giving me the correct result, I don't understand why pow(sum,1/2) is not considering that √x = x½.
Could you help me figure out what I am missing? Thank you! :-)
#include <stdio.h>
#include <math.h>
void print_vector(int N,float * V);
void save_vector(int N,float * V);
void absolute_values(int N,float * V, float * VABS);
void maximum_value(int N, float * VABS);
void general_norm(int N, float * VABS);
int main(void)
{
const int n=4;
int i;
float v[n],vabs[n];
puts("Enter the 5 components of the vector:");
save_vector(n, v);
puts("\nThe vector is:");
print_vector(n, v);
puts("\nThe absolute vector is:");
absolute_values(n, v, vabs);
puts("\nThe maximum value is:");
maximum_value(n, vabs);
puts("\nThe general norm is:");
general_norm(n, vabs);
return 0;
}
void save_vector(int N, float * V)
{
int i;
for(i=0;i<N;i++)
scanf("%f",V+i);
}
void print_vector(int N, float * V)
{
int i;
for(i=0;i<N;i++)
printf(" %.2f ",*(V+i));
}
void absolute_values(int N, float *V, float *VABS)
{
int i;
for(i=0;i<N;i++)
{
VABS[i]=((V[i]<0)?-V[i]:V[i]);
printf(" %f", VABS[i]);
}
}
void maximum_value(int N, float * VABS)
{
int i;
float maximum;
maximum = VABS[0];
for (i = 1; i < 4; i++)
{
if (VABS[i] > maximum)
{
maximum = VABS[i];
}
}
printf(" %f", maximum);
}
void general_norm(int N, float * VABS)
{
int i;
float sum;
for (i = 0; i < 4; i++)
{
sum=sum+pow(VABS[i],2);
}
printf(" %f",sqrt(sum));
printf(" %f",pow(sum,1/2));
}
Just leaving here the answer 1201ProgramAlarm gave me:
Integer math. 1/2 is 0. Either use 0.5, or force the type 1.0 / 2.0.
1.0 / 2 would also work.

Trying to write a program to fill an array with random numbers in C

My issue is that I am getting segmentation fault (core dumped) each time I try, I have yet to clean up my code, but I am stumped.
I must enter the values in with the compiler e.g "./filename 0 100" whereby 0 is min and 100 is max.
It must then fill the array of 10 elements with random numbers (0-100). I am so close, just can't fathom the main function.
Also, how can I print the array {0,1,2,3} in format "[0,1,2,3]" including the commas, without it looking like "[0,1,2,3, ]"
#include <stdlib.h>
#include <stdio.h>
int getRandom(int min, int max);
void fillArray(int data[], int size, int min, int max);
void printArray(int data[], int size);
int main(int argc, char *argv[]) {
int a;
int b;
if (argc>=3){
a = atoi(argv[1]);
b = atoi(argv[2]);
int arr[10];
printf("\t An array with random values from 0 to 100 \n");
fillArray(arr,10 ,a, b);
printArray(arr, 10);
} else {
printf("Incorrect number of arguments - please call with assignment min max\n");
}
return 0;
}
int getRandom(int min, int max) {
int result = 0;
int low = 0;
int high = 0;
if (min<max) {
low = min;
high = max+1;
} else {
low = max + 1;
high = min;
}
result = (rand() % (high-low)) + low;
return result;
}
void fillArray(int data[], int size, int min, int max){
int i;
for(i=min ; i < max+1; i++){
data[i] = getRandom(min,max);
}
}
void printArray(int data[], int size){
int i;
printf("[");
for(i=0; i<size; i++){
printf("%d,", data[i]);
}
printf("]");
}
I agree with #Steve Friedl that the main problem with your program lies in the fillArray function. There i should run from 0 to size.
As for your second question, testing whether you're printing the last number helps to suppress the unwanted comma:
void printArray(int data[], int size) {
printf("[");
for (int i = 0; i < size; i++) {
printf("%d", data[i]);
if (i < size - 1)
printf(",");
}
printf("]");
}
If you prefer a more compact solution (although with an optimizing compiler there's not really a difference), you could write it as:
void printArray(int data[], int size) {
printf("[");
for (int i = 0; i < size; i++) {
printf("%d%c", data[i], i < size-1 ? ',' : ']');
}
}
Also, in your main function, you should include a and b in your printing:
printf("\t An array with random values from %d to %d \n", a, b);
I believe this is blowing things up for you:
void fillArray(int data[], int size, int min, int max){
int i;
for(i=min ; i < max+1; i++){ // <-- HERE
data[i] = getRandom(min,max);
}
}
The calling function allocates 10 items in the arr array, and that's passed as the size parameter, but you're not using that parameter to limit filling up the array. If the max value is 100, then it's trying to fill one hundred slots instead of just ten.
for (i = 0; i < size; i++)
data[i] = getRandom(min,max);
should fix at least this issue.
EDIT: The comma thing, I prefer to add commas before the items unless this is the first. In this case it doesn't matter much, but it's more general, especially for variable-length lists where you don't know you're at the end until you get there. Augmenting the helpful response from #JohanC :
void printArray(int data[], int size) {
printf("[");
for (int i = 0; i < size; i++) {
if (i > 0) printf(",");
printf("%d", data[i]);
}
printf("]");
}

Function in C not returning correct data after I include another function

I am writing a program that creates an array of ten integers. I have to define max 10 constant and use functions.getdata(ask user for numbers),displaydata(display)
displaylargest,smallest,average,range,and median.
I am stuck on average because soon as I added that function my largest displays a weird number but if I comment out the average function my largest displays correct answer. Can someone tell me where I went wrong?
#include <stdio.h>
#define MAX 10
int getdata(int array[]);
int displaylargest(int array[]);
int displaysmallest(int array[]);
int displayaverage(int array[]);
void displaydata(int array[]);
int main () {
int array[MAX];
int largest;
int smallest;
int average;
printf("\nEnter ten numbers \n\n");
getdata(array);
displaydata(array );
largest=displaylargest( array);
printf("\nThe largest %d\n", largest);
smallest=displaysmallest( array);
printf("\nThe smallest is %d\n", smallest);
average=displayaverage(array);
printf("\nThe average is %d\n", average);
return 0;
}
int getdata(int array[]) {
int x;
printf ("Enter a number\n ",x+1);
for(x=0;x<MAX;x++)
scanf ("%d",&array[x]);
}
int displaylargest(int array[]) {
int x, largest=array[x];
for (x=0; x<MAX; x++) {
if (array[x]>largest)
largest=array[x];
}
return(largest);
}
int displaysmallest(int array[]) {
int x, smallest=array[x];
for (x=0; x<MAX; x++) {
if (array[x]<smallest)
smallest=array[x];
}
return(smallest);
}
int displayaverage(int array[]) {
int x;
int sum=0;
int average;
for (x=0; x<MAX; x++) {
sum+=array[x];
}
{
average=sum/MAX;
}
return(average);
}
void displaydata(int array[]) {
int x;
for(x=0; x<MAX; x++) {
printf("%d, ",array[x]);
}
}
You need to initialize local variables in your functions especially when you are using that to access your array. Without that local variable can contain any value ,if you use that as index to your array, you might be accessing valid memory.
#include <stdio.h>
#define MAX 10
void getdata(int array[]);
int displaylargest(int array[]);
int displaysmallest(int array[]);
int displayaverage(int array[]);
void displaydata(int array[]);
int main() {
int array[MAX];
int largest;
int smallest;
int average;
printf("\nEnter ten numbers \n\n");
getdata(array);
displaydata(array);
largest = displaylargest(array);
printf("\nThe largest %d\n", largest);
smallest = displaysmallest(array);
printf("\nThe smallest is %d\n", smallest);
average = displayaverage(array);
printf("\nThe average is %d\n", average);
return 0;
}
void getdata(int array[]) {
int x;
printf("Enter a number\n " );
for (x = 0; x<MAX; x++) {
scanf("%d", &array[x]);
}
}
int displaylargest(int array[]) {
int x, largest = array[0];
for (x = 0; x<MAX; x++) {
if (array[x]>largest)
largest = array[x];
}
return(largest);
}
int displaysmallest(int array[]) {
int x, smallest = array[0];
for (x = 0; x<MAX; x++) {
if (array[x]<smallest)
smallest = array[x];
}
return(smallest);
}
int displayaverage(int array[]) {
int x;
int sum = 0;
int average;
for (x = 0; x<MAX; x++) {
sum += array[x];
}
{
average = sum / MAX;
}
return(average);
}
void displaydata(int array[]) {
int x;
for (x = 0; x<MAX; x++) {
printf("%d, ", array[x]);
}
}
In c if we have local variable without initialization ,then it will have some garbage value. And in many of the functions u are intializing somevalue = array(x) it is not correct. The location you are accessing on the array is not valid.Make those chages it will work correctlu
Local variables need to be used here. While defining
largest=array[x];
make sure that x=0, else x may contain garbage value and the array may try to access invalid memory locations, leading to either the conditions known as underflow or overflow.
Also, I see that you've declared getdata() of type int, though it is not returning any value. Please make it of type void, as is just used to insert the asked values into the array. Hope this helps!

Resources