Function Template Assignment
Apr 13, 2020 at 6:23pm UTC
Figured it out Thanks
Last edited on Apr 13, 2020 at 8:07pm UTC
Apr 13, 2020 at 6:40pm UTC
If i introduce something like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
cout << "0 = int array" << endl;
cout << "1 = char array" << endl;
cout << "2 = float array" << endl;
cout << "Please enter a number that corresponds to the array you will enter." << endl;
cin >> UserSelect;
if (UserSelect == 0)
{
T = int ;
}
if (UserSelect == 1)
{
T = char ;
}
if (UserSelect == 2)
{
T = float ;
}
Am I headed in the right direction?
Apr 13, 2020 at 7:24pm UTC
I removed the input verification and added the template.
Still working on it but heres what I got so far:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
// Sorts a float array using bubble sort algorithm
#include <iostream>
#include <iomanip>
using namespace std;
const int arraySize = 100; // Const declaration and initialization
template <typename T>
void arrayEntry (T[], int );
template <typename T> // function protype - float array entry
void printArray (T[], int );
template <typename T> //function prototype - printing float array
void bubblesort (T[], int ); // function prototype - sorting float array
int UserSelect;
int main()
{
float x[ arraySize ]; // Array declaration
int number;
// Enter number of points
cout<< " Please, enter number of points between 1 and 100 " ;
cin >> number;
// Data entry
cout << "Please enter values for the element of the array X " << endl;
arrayEntry( x, number);
// Printing entered elements
cout<< endl << " Entered values" <<endl;
printArray ( x, number);
// sorting array x
bubblesort (x, number);
// Printing sorted array
cout << endl << " Sorted array" << endl;
printArray( x, number);
return 0; // indicates successful termination
} // end main
template <typename T>
void arrayEntry(T a[], int n)
{
int i;
for (i= 0; i<n; i++)
{
cout << "Element[" <<setw(2)<< i << "] = " ;
cin >> a[i];
}
}
template <typename T>
void printArray( T a[], int n)
{
for (int i=0; i<n; i++)
cout <<fixed << setprecision(2) <<"Element[" <<setw(2)<< i << "] = "
<<setw(10)<< a[i] << endl;
}
template <typename T>
void bubblesort ( T a[], int n)
{
float temp;
int pass, i;
// loop to control number of passes
for (pass=0; pass< n; pass++)
// loop to control number of comparisons per pass
for (i=0; i<n-1; i++)
if (a[i] > a[i+1]) //swapping
{
temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
}
}// end bubblesort
Last edited on Apr 13, 2020 at 7:25pm UTC
Topic archived. No new replies allowed.