array i have been trying to swap the minimum with the maximum number but i couldn't get it

Write your question here.


# include <iostream>
# include <algorithm>
using namespace std;
int main()
{
int n[5] = { 11, 23, 14, 16, 17 };
int min, minpos, max, maxpos, swap, i;
min = n[0]; minpos = 0; max = n[0]; maxpos = 0;
for (i = 0; i < 5; i++)
{
if (min > n[i]){ min = n[i]; minpos = i; }
if (max < n[i]){ max = n[i]; maxpos = i; }
}
swap = n[minpos];
n[minpos] = n[maxpos];
n[maxpos] = swap;
for (i = 0; i < 5; i++)cout << n[i] << endl;
system("pause");
return 0;
}
It works for me. What problems are you having?
i had a problem with the file so i had to open another file and wrote that same code on it and it work

you could also use a regular array with this instead of vector.begin() you'd do something like begin(array).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

 vector<int> i{ 1,2,3,4,5 };

    auto min = min_element(i.begin(), i.end());
    auto max = max_element(i.begin(), i.end());

    swap(*min, *max);

    for (auto m : i) {
        cout << m;
    }
You could also say
1
2
auto [min, max] = std::minmax_element(std::begin(array), std::end(array));
std::iter_swap(min, max);
Topic archived. No new replies allowed.