Search code examples
carraysfunction-callfunction-definition

Function for addition and getting average of a user defined single dimensional array


This is the question "Write a function which gets an integer array and number of elements as parameters and calculates and displays sum and average of all the integers of the array in C language"

Below is the code which I have done, it's running but consists of bugs which give false answers

#include <stdio.h>

void SumAvg(int x, int arr[x]) {
  int i, sum = 0;
  float avg = 0;

  for (i = 0; i < x; ++i) {
    sum += arr[i];
  }
  avg = (float)sum / x;

  printf("The sum is %d", sum);
  printf("\nThe average is %.2f", avg);
}

int main() {
  int x, i;

  printf("Enter number of elements");
  scanf("%d", &x);

  int arr[x];

  for (i = 0; i < x; ++i) {
    printf("Enter integers for array[%d]", i + 1);
    scanf("%d", &arr[i]);
  }
  SumAvg(x, arr[x]);

  return 0;
}

Solution

  • First , your function calling is wrong .It should be SumAvg(x,arr) instead of SumAvg(x, arr[x]);.

    also in function declaration , in some compiler void SumAvg(int x, int arr[x]) might be problematic.