There is a task to find the maximum and minimum element in the array, and swap them. I found such an example, but I don’t know how to output a modified array:

#include <iostream> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ using namespace std; int main(int argc, char** argv) { int a; int N; int b; int c; int k; int g; int arr[N]; int max = arr[0]; int min = arr[0]; cout << "vvedit N="; cin >> N; cout << "vvedit massiv"; for (int i = 0; i < N; i++) { cin >> arr[i]; } for (int i = 0; i < N; i++) { if (max < arr[i]) { max = arr[i]; k = i; } if (min > arr[i]) { min = arr[i]; g = i; } } a = max = k; b = min = g; c = a; a = b; b = c; cout << "max=" << max << endl; cout << "min=" << min << endl; for (int i = 0; i < N; i++) { cout << arr[i]; } system("pause"); return 0; 
  • No, they did not find and did not change - Igor
  • Found - yes, swapped - no - DNS
  • You do not have lines in the code that change two elements in places, which is why on the screen you will see the "correct" result of executing this code, and not the desired result. - nick_n_a
  • @nick_n_a How can the “correct” result be “on the screen” if min / max initialized before the array is entered? - Igor
  • You have no assignment in the code, i.e. missing line arr[???]=??? (??? is the correct expression) so the array remains unchanged. You did not complete the task - you did not swap them. - nick_n_a

1 answer 1

Oh, something you keep back :)

Well, how can this compile at all, and even work - I do not understand:

 int N; int arr[N]; int max = arr[0]; 

Here you go:

 #include <vector> #include <iostream> #include <iomanip> using namespace std; int main() { unsigned int N; cout << "Number of items: "; cin >> N; vector<int> a(N); for(size_t i = 0; i < N; ++i) { cout << "a["<<i<<"] = "; cin >> a[i]; } int min, max; size_t imin, imax; min = max = a[imin = imax = 0]; for(size_t i = 0; i < N; ++i) { if (a[i] > max) { imax = i; max = a[i]; } else if (a[i] < min) { imin = i; min = a[i]; } } int tmp = a[imax]; a[imax] = a[imin]; a[imin] = tmp; cout << "max = " << max << endl; cout << "min = " << min << endl; for(size_t i = 0; i < N; ++i) { cout << "a["<<i<<"] = " << a[i] << endl; } } 

If it is necessary through arrays, replace

 vector<int> a(N); 

on

 int * a = new int[N]; 

and before exiting main add the delete[] a; .