LLP
LLP

Reputation: 71

Getting Error While Calculating Average in Array More Than 4 Elements in C

I did the below program in C. It works fine up to number 4, if you type number 5 forward I'm getting Segmentation fault: 11 error? Why? I cannot find where is the error. Thank you.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void)
{ 
  srand(time(NULL));
  
  int sum, i, input;
  int array [input];
  float average;
  sum = average = 0;
  int size = sizeof (array) / sizeof(array[0]);

  printf("Type the value of your array : ");
  scanf("%d", &input);

  printf("The size of your array is : %.2d \n", input);

  for (i = 0; i < input; i++)
  {
    array[i] = rand() % 100 + 1;
  }

  // loop for printing results

  for (i = 0; i < input; i++)
  {
    printf("Element %d; %d \n", i, array[i]);
  }
 
  for(i = 0; i < input; i ++){
    sum = sum + array[i];
  }

  average = (float)sum / i;
  printf("The average of array values is %.2f \n", average);
  
  
  return 0;
  };  

Upvotes: 1

Views: 105

Answers (1)

Rohan Bari
Rohan Bari

Reputation: 7726

The defects in the code:

  1. Used the variable input uninitialized to initialize an array.

  2. Attempted to get the size of the array which has incorrectly determined previously.

  3. The variable size is never used in the entire program (redundant declaration).

Note: I'll be using -std=c99 (C99 standard)

gcc -std=c99 -o main main.c; ./main

Code redefined (read the added comment to get the issue solved):

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void) {
    srand(time(NULL));

    int sum, i, input;
    float average;
    sum = average = 0;

    printf("Type the value of your array : ");
    scanf("%d", &input);

    int array[input]; // placing after defining of 'input'
    // int size = sizeof(array) / sizeof(array[0]); // unused variable

    printf("The size of your array is : %.2d \n", input);

    for (i = 0; i < input; i++)
        array[i] = rand() % 100 + 1;

    // loop for printing results

    for (i = 0; i < input; i++) {
        printf("Element %d; %d \n", i, array[i]);
        sum += array[i];
    }

    average = (float) sum / i;

    printf("The average of array values is %.2f \n", average);

    return 0;
};

This will output:

Type the value of your array : 10 
The size of your array is : 10 
Element 0; 6
Element 1; 14
Element 2; 66
Element 3; 73
Element 4; 19
Element 5; 14
Element 6; 62
Element 7; 78
Element 8; 31
Element 9; 31
The average of array values is 39.40

Upvotes: 3

Related Questions