In C++: Run a program that: Prompts the user to enter an array of 3 records, eac
ID: 3715730 • Letter: I
Question
In C++:
Run a program that:
Prompts the user to enter an array of 3 records, each having a different company name string and a different profit dollar amount. Use a for-loop.
Passes the the record array to a function that displays it to the console.
Passes the record array to a function that copies the array to a new dynamic record array, sorts the new record array by company name, and returns a pointer to the new sorted record array.
Passes the new sorted record array to a function that displays it to the console.
Example program output display:
Enter company name: Fay's Wraps
Enter its annual profit: 213032
Enter company name: John's Repair Shop
Enter its annual profit: 1055214
Enter company name: D&H Consultants
Enter its annual profit: -4300
Original Record Array:
Fay's Wraps 213032
John's Repair Shop 1055214
D&H Consultants -4300
Sorted Record Array:
D&H Consultants -4300
Fay's Wraps 213032
John's Repair Shop 1055214
Explanation / Answer
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
class company
{
public:
string name;
string profit;
};
//method to copy
company* copy(company a[],int n)
{
company *p = new company[n];//dynamically creating memory
//copying a to p
int i=0;
while(i<n)
{
p[i].name = a[i].name;
p[i].profit = a[i].profit;
i++;
}
//sorting...by name...
int j=0;
i=0;
while(i<n)
{
j=i;
while(j<n)
{
string p1,p2;
if(p[j].name.compare(p[i].name)<0)
{
//swapping
p1 = p[i].name;
p2 = p[i].profit;
p[i].name=p[j].name;
p[i].profit=p[j].profit;
p[j].name=p1;
p[j].profit=p2;
}
j++;
}
i++;
}
//after sorting...
return p;
}
int main()
{
int i=0;
company a[3];
while(i<3)
{
cout<<"Enter company name:";
getline(cin,a[i].name);
cout<<"Enter it's annual profit:";
getline(cin,a[i].profit);
i++;
}
company *p = copy(a,3);
cout<<"Original Record Array: ";
i=0;
while(i<3)
{
cout<<a[i].name<<" "<<a[i].profit<<endl;
i++;
}
cout<<"Sorted Record Array: ";
i=0;
while(i<3)
{
cout<<p[i].name<<" "<<p[i].profit<<endl;
i++;
}
return 0;
}
output:
Enter company name:Fay's Wraps
Enter it's annual profit:213032
Enter company name:John's Repair Shop
Enter it's annual profit:1055214
Enter company name:D&H Consultants
Enter it's annual profit:-4300
Original Record Array:
Fay's Wraps 213032
John's Repair Shop 1055214
D&H Consultants -4300
Sorted Record Array:
D&H Consultants -4300
Fay's Wraps 213032
John's Repair Shop 1055214
Process exited normally.
Press any key to continue . . .