Reputation: 115
This is a simple program, that finds teh smallest and largest element of a 10-array. I'm not sure why I'm getting the segmentation fault(core dumped) error.
#include <stdio.h>
int main(void) {
int i, j, min, array[10], max, n;
//This loop get user input for the elements of the array
for(i = 0; i < 10; i++) {
printf("Enter element number %d:", i);
scanf("%d", &n);
array[i] = n;
}
min = array[0];
max = array[0];
//This loop finds the smallest element of the array
for(j = 0; j < 10; j++) {
if(min > array[j]) {
min = array[j];
}
}
//This loop finds the largest element of the array
for(j = 9; j >= 0; j++) {
if(max < array[j]) {
max = array[j];
}
}
printf("smallest value is: %d", min);
printf("largest value is: %d", max);
return 0;
}
Upvotes: 1
Views: 93
Reputation: 115
The loop below tries to point to a location that is beyond the assigned memory space.
for(j = 9; j >= 0; j++)
Instead try writing:
for(j=9; j >= 0; j--)
You may go for, an incrementing loop, as suggested by @mch, if you you'd like.
Also, as a suggestion, skip using the variable j
here. You can use i
instead. Won't be any issues, since you are assigning 0
to it in loop. You'd be saving 4 precious bytes.
Upvotes: 0
Reputation: 9814
for(j = 9; j >= 0; j++)
should be
for(j = 9; j >= 0; j--)
if you want to iterate from the last to the first. You access array[10]
in the second iteration, which is out of bounds.
Also there is no reason to iterate from the last to the first, so
for(j = 0; j < 10; j++)
would also work.
You can do the whole job in a single for loop (reading from stdin, look if it is larger than the max/smaller than the min) and so you do not need the array.
Upvotes: 4
Reputation: 26747
for (j = 9; j >= 0; j++)
Here you start from 9 and do j++!
do this:
for (j = 9; j >= 0; j--)
By the way you can do this
scanf("%d", array + i);
Upvotes: 1