Answer to Question #214590 in C++ for Waol

Question #214590

Using vector class library, read 12 numbers from a file and push into a vector “vect1”. Write the following functions:

      1- Swap the first element in the list with the min value .

      2- Swap the last element in the list with the max value

      3- Return the median.


1
Expert's answer
2021-07-07T18:28:18-0400

//With test abd screen capture

//sorry fixed bug this right version
#include <iostream>
#include <vector>
#include <fstream>
#include <algorithm>
using namespace std;
//function swap first with minimum
void swapfmn(vector<int>& a)
{
    int ind = 0;//index minimum
    for (int i = 0; i < a.size(); i++)
        if (a[i] < a[ind])
            ind = i;//find the minimum
    int tm = a[0];
    a[0] = a[ind];
    a[ind] = tm;
}
//swap last with maximum
void swaplmx(vector<int>& a)
{
    int ind = 0;//index max
    for (int i = 0; i < a.size(); i++)
        if (a[i] > a[ind])
            ind = i;//find the max
    int tm = a[a.size() - 1];
    a[a.size() - 1] = a[ind];
    a[ind] = tm;
}
//find median
double median(vector<int> scores)
{
    size_t size = scores.size();
    if (size == 0)
    {
        return 0;  // Undefined, really.
    }
    else
    {
        sort(scores.begin(), scores.end());
        if (size % 2 == 0)
        {
            return (scores[size / 2 - 1] + scores[size / 2]) / 2;
        }
        else
        {
            return scores[size / 2];
        }
    }
}
int main() {
    /*
    you must create an input.txt
    and write 12 numbers file before running the program
   */
    ifstream fin("input.txt");
    if (!fin)
        cout << "File not found Please create file\n";
    vector<int>vi;//initiliazed vector 
    for (int i = 0; i < 12; i++)
    {
        int num;
        fin >> num;//read number file
        vi.push_back(num);
    }
    swapfmn(vi);//swap minimum with first
    swaplmx(vi);
    for (int i = 0; i < 12; i++)
        cout << vi[i] << " ";
    cout << endl;
    cout << "median: " << median(vi) << endl;
    fin.close();
    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS