How to find the closest elements of average in C? - arrays

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
}

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

Sum the first n numbers (from 1 to n) using loops in C

I want to create an algorithm that allows you to sum the first n numbers (from 1 to n) once the user is asked to enter n from the keyboard.
#include <stdio.h>
int main() {
int x,k,j;
scanf("%d",&x);
int y= 1;
do {
int k= y;
int y= y+1;
int j= k+y;
} while(y<x);
printf("The Total sum of the number is: %d ", j);
}
I have wrote this but it gives me this error:
[Error] ld returned 1 exit status
You already initialized y, j and k. There is a simplier way to count sum from 1 to n.
scanf("%d", &n);
int sum=0;
for(int i=1; i<=n; i++){
sum=sum+i;
}
1.Variables are not initialized.
2.Re-create variables too many times resulting in no saved values.
3.Hard to read.
Try this:
#include <stdio.h>
int main() {
int end = 0, sum = 0;
scanf("%d",&end);
int i = 1;
do {
sum = sum + i;
i= i+1;
} while(i<=end);
printf("The Total sum of the number is: %d ", sum);
}

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

Recursive function calculating average from int array three by three elements

Calculating average three by three elements and replacing those elements with the average result.
Example array [1,2,7,-2,5,0, 2,8]
After transformation [3,3,3,1,1,1,5,5]
Something is wrong, I can't get it to work.
#include <stdio.h>
int main ( ) {
int n, c[n];
int *avg;
int pom=0;
printf("Enter lenght of array\n");
scanf("%d",&n);
printf("Enter elements");
for(i = 0;i < n; i++)
scanf("%d",c[i]);
avg=Average(c , n, pom);
for(i = 0; i < n; i++)
printf("Avg elements= %d",*(avg+i))
return 0;
}
int Average(int arr[], int size, int z)
{
int k, l, m, Asum;
if (size < 0) {
return arr;
} else {
k=arr[z];
l=arr[z+1];
m=arr[z+2];
Asum=(k + l + m)/3;
arr[z]=Asum;
arr[z+1]=Asum;
arr[z+2]=Asum;
}
return Average(arr,size--,z++);
}
int n, c[n]; is a problem. n is uninitialized so the size of the array is who-knows-what? This is undefined behavior.
Instead
int main(void) {
int n;
int *avg;
int pom=0;
printf("Enter length of array\n");
if (scanf("%d",&n) != 1) return -1;
int c[n];
for(i = 0;i < n; i++)
// scanf("%d",c[i]);
scanf("%d",&c[i]); // pass the address of an `int`
Likely other issues too.
Try simple input first, imagine what happens when you enter only 1 number, what will the Average function do? Don't run the code but try to execute it in your head or with pencil and paper. If you think the program only has to work with three or more numbers, try three.
A serious program would explicitly reject invalid input.

"Uninitialized Local Variable" Error, Despite Defining Variable?

Here's the code. It says a variable is not initialized, despite defining it at the top of the code after main function.
#include<stdio.h>
int main()
{
int n, sum=0; i=0;
printf("Please enter a number to evaluate\n");
scanf_s("%d",&n);
for(i=0; i<=n; i++)
{
double(sum) = sum + double(1/n);
}
sum = (int)sum;
if(sum == 1)
{
printf("Adding %d 1/%d's gives a result of 1\n",n,n);
}
if(sum <= 1)
{
printf("Adding %d 1/%d's gives a result less than 1\n",n,n);
}
if(sum >= 1)
{
printf("Adding %d 1/%d's gives a result greater than 1\n",n,n);
}
return(0);
}
Either remove semicolon after sum=0; and change
int n, sum=0; i=0;
to
int n, sum=0, i=0;
or change int n, sum=0; i=0; to
int n, sum=0; int i=0;
Side Note:
The statement
double(sum) = sum + double(1/n);
is wrong. If you mean double(sum) by casting then it is not a valid syntax. If it would be like (double)sum then still it is wrong as = require l-value as its left operand.
I would suggest you to declare sum as double and rewrite it as
int n = 1, i;
printf("Please enter a number to evaluate\n");
scanf_s("%d",&n);
double sum = 0.0;
for(i=0; i<=n; i++)
{
sum = sum + (1.0/n);
}
What happens if scanf_s fails? You need to initialize n.

Resources