I'm getting values but not as it should be - arrays

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;
}

Related

"assignment makes integer from pointer without a cast"?

I'm really new to this. I've never done anything like this so I'm having issues with this code. I was given a template to write my code in separate functions like this, although I added the findPos one myself. I'm getting the "assignment makes integer from pointer without a cast" warning and also my max, min, sum, avg, and position of max and min are obviously not coming out to the right numbers. I was just wondering if anyone can lead me in the right direction.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int findMin(int arr[], int size);
int findMax(int arr[], int size);
int findSum(int arr[], int size);
int findPos(int arr[], int size);
int size;
int i;
int max;
int min;
int avg;
int sum;
int pos;
int main()
{
srand(time(0));
printf("Enter an integer: ");
scanf("%d", &size);
int arr[size];
max = findMax;
min = findMin;
pos = findPos;
sum = findSum;
avg = sum / size;
printf("max:%7d\tpos:%d\t\n", max, pos);
printf("min:%7d\tpos:%d\t\n", min, pos);
printf("avg:%7d\n", avg);
printf("sum:%7d\n", sum);
printf("\n");
printf(" Pos : Val\n");
printf("-------------\n");
for (i = 0; i < size; i++) {
arr[i] = (rand() % 1001);
printf("%4d :%6d\n", i, arr[i]);
}
return 0;
}
int findMin(int arr[], int size)
{
min = arr[0];
for (i = 0; i < size; i++) {
if (arr[i] < min) {
min = arr[i];
}
}
return min;
}
int findMax(int arr[], int size)
{
max = arr[0];
for (i = 0; i < size; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
int findSum(int arr[], int size)
{
sum = 0;
for (i = 0; i < size; i++) {
sum = sum + arr[i];
}
return sum;
}
int findPos(int arr[], int size)
{
for (i = 0; i < size; i++) {
pos = i;
}
return pos;
}
max = findMax;
min = findMin;
pos = findPos;
sum = findSum;
You're assigning function pointer, not return value, to integer variable. You have to do something like max = findMax(arr, size). Also in that case, you should assign values to arr before calling it.
There are a couple of issues with the code. Let me iterate through the same
Populating Data in Created Array
Since the data has to present the created array before performing any operations,
printf("\n");
printf(" Pos : Val\n");
printf("-------------\n");
for (i = 0; i < size; i++) {
arr[i] = (rand() % 1001);
printf("%4d :%6d\n", i, arr[i]);
}
this snippet should be reordered and moved above the function calls and just after the int arr[size];
Function Calls
All your functions, namely findMax,findMin,findPos,findSum is expecting two parameters
arr - array you have created
size - the size value read from scanf()
Assuming you want to store the return value from the function in the main int variables max,min,pos,sum,avg
the statements
max = findMax;
min = findMin;
pos = findPos;
sum = findSum;
should be replaced with function calls like
max = findMax(arr, size);
min = findMin(arr, size);
pos = findPos(arr, size);
sum = findSum(arr, size);
The Final Main code will be
int main()
{
srand(time(0));
printf("Enter an integer: ");
scanf("%d", &size);
int arr[size];
printf("\n");
printf(" Pos : Val\n");
printf("-------------\n");
for (i = 0; i < size; i++) {
arr[i] = (rand() % 1001);
printf("%4d :%6d\n", i, arr[i]);
}
max = findMax(arr, size);
min = findMin(arr, size);
pos = findPos(arr, size);
sum = findSum(arr, size);
avg = sum / size;
printf("max:%7d\tpos:%d\t\n", max, pos);
printf("min:%7d\tpos:%d\t\n", min, pos);
printf("avg:%7d\n", avg);
printf("sum:%7d\n", sum);
return 0;
}

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
}

Finding largest and min number in an array with functions

I am trying to write a C program that calculates the min and max value from entered numbers. I managed find the min and max value, but for some reason i cannot print out the values outside the function. This is my code:
#include <stdio.h>
#include <stdlib.h>
void find_largest_smallest(int a[], int n, int *largest, int *smallest)
{
largest=smallest=a[0];
int i;
for(i=0; i<n; i++)
{
if (largest<a[i])
largest=a[i];
}
for(i=0; i<n; i++)
{
//printf("%d\n", a[i]);
if (smallest>a[i])
smallest=a[i];
}
printf("Largest is %d\n", largest);
printf("smallest is %d\n", smallest);
}
int main()
{
int elem;
int i;
int *x;
int *y;
printf("How many elements you want to store ?:");
scanf("%d", &elem);
int store[elem];
for(i=0; i<elem; i++)
{
printf("Enter a value to be stored:");
scanf("%d", &store[i]);
}
find_largest_smallest(store, elem, &x, &y);
printf("Largest value stored is %d and the smallest is %d.", *x, y);
return 0;
}
This:
largest=smallest=a[0];
Is wrong. You are assigning an integer to a pointer. What you should do is instead:
*largest = a[0];
*smallest = a[0];
Same goes for other assignments and reads:
if (*largest < a[i])
*largest = a[i];
/* ... */
if (*smallest > a[i])
*smallest = a[i];
/* ... */
printf("Largest is %d\n", *largest);
printf("smallest is %d\n", *smallest);
The declaration of x and y in main should just be int (not int *):
int x, y;
The call to printf in main is also wrong:
printf("Largest value stored is %d and the smallest is %d.", x, y);
// no asterisk needed here ----------^
The parameters largest and smallest have pointer types
void find_largest_smallest(int a[], int n, int *largest, int *smallest)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
So within the function you have to dereference the pointers to access pointed objects.
For example
void find_largest_smallest(int a[], int n, int *largest, int *smallest)
{
*largest = *smallest = a[0];
int i;
for ( i = 1; i<n; i++ )
{
if ( *largest<a[i] )
*largest=a[i];
}
for ( i = 1; i<n; i++ )
{
//printf("%d\n", a[i]);
if ( *smallest>a[i] )
*smallest=a[i];
}
printf("Largest is %d\n", *largest);
printf("smallest is %d\n", *smallest);
}
Pay attention to that you could find the largest and the smallest elements using only one loop. Apart this the function should calculates pointers to the largest and smallest elements instead of their values because in general the user can pass the size of the array equal to 0. In this case the function will have undefined behavior.
Also within main the variables x and y should have the type int. That is
int x;
int y;
//...
printf("Largest value stored is %d and the smallest is %d.", x, y );

C - maximum value from one dimensional array's groups

So, my task is to let user fill one dimensional array A. This array has M number of groups and P members in each group. I need to fill array B with maximum values of each group in A array and display results of maximum values in each group after. I couldn't figure out any way to do it. I would really appreciate your help since I am a beginner programmer and doing my best to study. So my main problem in code is fillBArray function.
#include <stdio.h>
#include <stdlib.h>
int checkingvariable(int k, int a, int b);
void fillArray(int M, int P,int A[]);
void printArray(int M, int P,int A[]);
void fillBArray(int M, int P,int A[]);
int main()
{
int M, P;
printf("Enter M (the number of groups): ");
scanf("%d", &M);
M=checkingvariable(M, 1, 10);
printf("Enter P (the number of cars in one group): ");
scanf("%d", &P);
P=checkingvariable(P, 1, 10);
int i = P*M;
int A[i];
fillArray(M, P, A);
printArray(M, P, A);
fillBArray(M, P, A);
return 0;
}
void printArray(int M, int P,int A[])
{
int i;
for (i=0 ; i< M*P ; i++)
{
printf("%d ", A[i]);
printf("\n");
}
}
void fillArray(int M, int P, int A[])
{
int i;
for (i=0 ; i< M*P ; i++)
{
printf("Enter speed of car %d: ", i+1);
scanf("%d", &A[i]);
}
}
void fillBArray(int M, int P, int A[])
{
int c, k=0;
int maximum = A[0];
int B[M], group;
for (c = 0; c < P*M; c++)
{
if (A[c] > maximum)
{
maximum = A[c];
}
maximum = B[k];
printf("Maximum value for %d group is: %d", group, maximum);
}
}
int checkingvariable(int k, int a, int b)
{
if (k<a || k>b)
{
while(k<a || k>b)
{
printf("Enter correct value between %d and %d: ", a, b);
scanf("%d", &k);
}
}
return k;
}
One way is to replace one loop with two nested loops. The outer loop would iterate groups, while the nested loop would iterate members in each group.
One observation before you begin: members of a group g in the array A are located between indexes g*P, inclusive, and (g+1)*P, exclusive. Member m of a group is located at the index A[g*P + m].
Now it should be clear how to make your loops:
for (int g = 0 ; g != M ; g++) { // Groups
int max = A[g*P];
for (int m = 1 ; m != P ; m++) { // Members
... // Compute max
}
// Store max for group g in B[]
}
#include <stdio.h>
#include <stdlib.h>
int checkingvariable(int k, int a, int b);
void fillArray(int M, int P,int A[]);
void printArray(int M, int P,int A[]);
void fillBArray(int M, int P,int A[]);
int main()
{
int M, P;
printf("Enter M (the number of groups): ");
scanf("%d", &M);
M=checkingvariable(M, 1, 10);
printf("Enter P (the number of cars in one group): ");
scanf("%d", &P);
P=checkingvariable(P, 1, 10);
int i = P*M;
int A[i];
fillArray(M, P, A);
printArray(M, P, A);
fillBArray(M, P, A);
return 0;
}
void printArray(int M, int P,int A[])
{
int i;
for (i=0 ; i< M*P ; i++)
{
printf("%d ", A[i]);
printf("\n");
}
}
void fillArray(int M, int P, int A[])
{
int i;
for (i=0 ; i< M*P ; i++)
{
printf("Enter speed of car %d: ", i+1);
scanf("%d", &A[i]);
}
}
/*void fillBArray(int M, int P, int A[])
{
int c, k=0;
int maximum = A[0];
int B[M], group;
for (c = 0; c < P; c++)
{
if (A[c] > maximum)
{
maximum = A[c];
}
if (c < P)
{
group = 1;
maximum = A[c];
printf("Maximum value for %d group is: %d", group, maximum);
}
if (c < P*2)
{
group = 2;
k=1;
maximum = A[c];
printf("Maximum value for %d group is: %d", group, maximum);
}
}
}*/
void fillBArray(int M, int P, int A[])
{
int B[M], maximum = 0, m;
for (int g = 0 ; g != M ; g++)// Groups
{
int max = A[g*P];
for (m = 0 ; m != P ; m++) // Members
{
if (A[g*P + m] > maximum)
{
maximum = A[g*P + m];
}
}
B[g] = maximum;
printf("Maximum value for %d group is: %d", g+1, maximum);
printf("\n");
maximum = 0;
}
}
int checkingvariable(int k, int a, int b)
{
if (k<a || k>b)
{
while(k<a || k>b)
{
printf("Enter correct value between %d and %d: ", a, b);
scanf("%d", &k);
}
}
return k;
}
This is answer to my problem, check fillBArray.

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

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);
}

Resources