a) Write a definition of a structure called Part, containing fields of item (str
ID: 3662882 • Letter: A
Question
a) Write a definition of a structure called Part, containing fields of item (string up to 20 characters), price (float) and quantity (integer).
b) Write a function with header void Display (Part p) which accepts a structure and prints all three fields. Note that this header uses “pass by value”.
c) Write a function float Cost (Part* p) which calculates the total cost of the parts. Note that this header uses “pass by address”.
d) This code creates an array of 5 parts: const int n = 5; Part p[5]; Write a for loop that uses the Cost function above to find the total cost of all 5 parts and print this total after the loop.
e) Write a function called TotalCost which as input takes the entire array of all 5 parts and calculates the total cost, returning this value. Here is a call statement: total = TotalCost (p, n); Write a program using all these functions, called inventory.CPP
Explanation / Answer
#include <iostream>
using namespace std;
struct Part {
string item;
float price;
int quantity;
}p[5];
void display(Part p);
float cost(Part* p);
float totalCost(Part p[],int n);
int main()
{
float total=0;
for(int i=0;i<5;i++){
p[i].item="Item"+i;
p[i].price=i;
p[i].quantity=i;
total=total+cost(&p[i]);
}
cout << "totalCost :" << total<<endl;
total = totalCost(p,5);
cout << "totalCost :" << total<<endl;
return 0;
}
void display(Part p){
cout <<"Item :"<< p.item<< endl;
cout << "Price :"<<p.price<< endl;
cout << "Quantity :"<<p.quantity<< endl;
}
float totalCost(Part p[],int n){
float totalCost=0;
for(int i=0;i<n;i++){
p[i].item="Item"+i;
p[i].price=i;
p[i].quantity=i;
totalCost=totalCost+cost(&p[i]);
}
return totalCost;
}
float cost(Part* p){
float total = p->quantity*p->price;
return total;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.