I need help with trying to do C++ functions; Two Functions: Times Table: Print o
ID: 3575261 • Letter: I
Question
I need help with trying to do C++ functions;
Two Functions: Times Table: Print out a Times Table (from 1 to 12) , Sorting Demo: given a vector: v = {2, 5, 10, 23, 7, 9, 111, 96, 34, 300, 65}, sort the vector from the largest to smallest (in descending order); and report the minimum, middle and maximum numbers. Also Command Control : t for [times table]; s for [sorting]; q to [quit program]. Out the results to Screen (cout) and a Text File (ofstream) and display the contents from the saved text file when user input/commend is ‘q’. Please show work. Thanks.
Explanation / Answer
// C++ code
#include <iostream>
#include <string.h>
#include <cstring>
#include <vector>
#include <fstream>
using namespace std;
void sortVector(std::vector<int> &v)
{
for (int i = 0; i < v.size(); ++i)
{
for (int j = 0; j < v.size(); ++j)
{
if(v[i] < v[j])
{
int t = v[i];
v[i] = v[j];
v[j] = t;
}
}
}
}
void timesTabel(std::vector<int> &v)
{
cout << "Vector: ";
for (int i = 0; i < v.size(); ++i)
{
cout << v[i] << " ";
}
cout << endl;
}
void output_To_File(std::vector<int> &v)
{
ofstream outFile;
outFile.open ("outfile.txt");
outFile << "Vector: ";
for (int i = 0; i < v.size(); ++i)
{
outFile << v[i] << " ";
}
outFile.close();
}
int main()
{
vector<int> v;
v.push_back(2);
v.push_back(5);
v.push_back(10);
v.push_back(23);
v.push_back(7);
v.push_back(9);
v.push_back(111);
v.push_back(96);
v.push_back(34);
v.push_back(300);
v.push_back(65);
char choice;
while(true)
{
cout << " t: Times Table s: Sorting q: Quit Enter your choice: ";
cin >> choice;
if(choice == 't')
{
timesTabel(v);
}
else if(choice == 's')
{
sortVector(v);
int min = v[0];
int max = v[v.size()-1];
int middle = v[v.size()/2];
cout << "Sorting done ";
}
else if(choice == 'q')
{
output_To_File(v);
timesTabel(v);
break;
}
else
cout << "Invalid Input ";
}
return 0;
}
/*
output:
t: Times Table
s: Sorting
q: Quit
Enter your choice: t
Vector: 2 5 10 23 7 9 111 96 34 300 65
t: Times Table
s: Sorting
q: Quit
Enter your choice: s
Sorting done
t: Times Table
s: Sorting
q: Quit
Enter your choice: q
Vector: 2 5 7 9 10 23 34 65 96 111 300
*/