Home > Software design >  C program the average value of the elements of the array
C program the average value of the elements of the array

Time:12-14

If the array element is twice as large as its predecessor (for example 1,2,3,4,.. in this case element 2 is twice as large as element before 2, which is 1) then program should make average value of these two elements (in this case 1 2 = 3, 3/2 = 1.5) and after making average value, program should put that value between these two numbers and print new array. (in this case new array would look like: 1, 1.5, 2, 3, 4, ...) Do you have any idea how to make this? Array consists of double numbers.

#include <math.h>
#include <stdio.h>
#define epsilon 0.0001
int main() {
  int i, k = 0, n;
  double arr[100];
  do {
    printf("Enter number of array elements: ");
    scanf("%d", &n);
  } while (n <= 0 || n > 100);
  printf("Enter array: ");
  for (i = 0; i < n; i  ) {
    scanf("%lf", &arr[i]);
  }
  for (i = 0; i < n; i  ) {
    if (fabs(arr[i   1] - 2 * arr[i]) < epsilon) {
     
    }
  }
  return 0;
}

CodePudding user response:

I think you need just check if next element is at least twice as large as previous and then print additional number in a sequence.

int main() {
  int i, k = 0, n;
  double arr[100];
  do {
    printf("Enter number of array elements: ");
    scanf("%d", &n);
  } while (n <= 0 || n > 100);
  printf("Enter array: ");
  for (i = 0; i < n; i  ) {
    scanf("%lf", &arr[i]);
  }
  printf("%f ", arr[0]);
  double med = 0;
  for (i = 0; i < n - 1; i  ) {
    if (arr[i 1] >= 2 * arr[i]) {
      med = (arr[i   1]   arr[i]) / 2;
      printf("%f ", med);
    }
    printf("%f ", arr[i 1]);
  }
  return 0;
}

Also change number of iterations to n-1.

CodePudding user response:

To address comments suggesting how to create array at runtime...

(and a few other suggestions are in comments in code below.)

Rather than creating an array with set size, create one with the number of elements decided by user by using a VLA. It is a form of dynamically placing an array into stack (as opposed to heap) memory, as such, it does not require use of calloc() et.al. so no need to call free() Example using your original code:

int main(void) {//main() is not a prototyped signature of main. Use void parameter.
  int i = 0 /*k = 0*/, n;//k is not used, init i

//double arr[100] = {0};//better to initialized before using
                    //and even better to use VLA (if using C99 or newer.)
  do {
        if(i   > 3) {//prevent infinite loop possibility
           printf("%s", "Exiting\n"); 
           return 0;    
        }
        printf("Enter number of array elements: ");
        scanf("%d", &n);
  } while (n <= 0 || n > 100);
  double arr[n];//Variable Length Array (VLA)
  memset(arr, 0, sizeof arr);/initialize to zero
  ...

Be sure to read the VLA link above, as VLA does have its caveats, but will work fine in the case of your code.

  • Related