Swap the largest and smallest elements in a given array.

Input: The first line number N, (N> 0) - the length of the array. The length of the array is not more than 100 elements. The second line is N of natural numbers, separated by spaces.

Output: A new array in which in place of the minimum element is the maximum element, and in place of the maximum is the minimum element. The remaining elements of the array remain in their original places.

Do not judge strictly, maybe the question is obsurd, but I just got to the arrays in studying C. So here is my decision:

#include <stdio.h> int main() { const int quantity; scanf("%d", &quantity); int arr[quantity]; for(int i = 0; i < quantity; i++) { scanf("%d", &arr[i]); } int max, min, i_min, i_max; min = max = arr[0]; for(int i = 0; i < quantity; i++) { if(min > arr[i]) { min = arr[i]; i_min = i; } else if(max < arr[i]) { max = arr[i]; i_max = i; } } for(int i = 0; i < quantity; i++) { if(i == i_min) { printf("%d ", arr[i_max]); } else if(i == i_max) { printf("%d ", arr[i_min]); } else { printf("%d ", arr[i]); } } return 0; } 

The last block is:

 for(int i = 0; i < quantity; i++) { if(i == i_min) { printf("%d ", arr[i_max]); } else if(i == i_max) { printf("%d ", arr[i_min]); } else { printf("%d ", arr[i]); } } 

Creates a problem Segmentation fault (core dumped), explain what is behind the gap, how to fix it and why the existing solution is not correct. Help me, please.

  • Output or look at debugging, what i_min and i_max are equal to. And if something is wrong, think about what caused it - MBo
  • const int quantity; scanf("%d", &quantity); - and what is this surrealism? What is suddenly const here? And who allowed you to read something in the const int variable? - AnT
  • I set up const to verify that I cannot change the value, although the compiler did not swear, and I forgot about it because it caused no problems. - Astrodynamic

1 answer 1

 int max, min, i_min, i_max; min = max = arr[0]; for(int i = 0; i < quantity; i++) { if(min > arr[i]) { min = arr[i]; i_min = i; } else if(max < arr[i]) { max = arr[i]; i_max = i; } } 

In this block, variables i_min and i_max are declared, that is, they have nothing to assign, they contain random values. That in most cases, prohibitively large values, which for obvious reasons are not included in the initialized array. These values ​​do not change if max or min value comes first in the array and so its value remains garbage. Error in this case due to the appeal to a non-existent element of the array.

  • OK, well, that figured out - MBo