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.
const int quantity; scanf("%d", &quantity);- and what is this surrealism? What is suddenlyconsthere? And who allowed you to read something in theconst intvariable? - AnT