Reputation: 71
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
Reputation: 7726
The defects in the code:
Used the variable input
uninitialized to initialize an array.
Attempted to get the size of the array which has incorrectly determined previously.
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