In: Computer Science
Suppose that class OrderList has a private attribute double cost[100] which hold the cost of all ordered items, and a private attributes int num_of_items which hold the number of items ordered. For example, if num_of_items is 5, then cost[0], cost[1], ..., cost[4] hold the cost of these 5 items. Implement the member function named total_cost which returns the total cost of this OrderList.
In the c++ code below we have a class called OrderList that has two data members- cost[] that stores cost of each item and n_of_items that stores number of items.
And then we have a member function total_cost() that calculates and returns the total cost of the items.
First, it asks user to enter the number of items and then runs a for loop that number of times to gat the cost of each item from the user. Simultaneously, it sums up the costs and finally returns the sum.
CODE:
#include<iostream>
using namespace std;
class OrderList
{
private:
double cost[100];
int num_of_items;
public:
double total_cost() //defining the member function
{
int i;
double sum = 0; //to get the total cost
cout<<"Enter the number of items: ";
cin>>num_of_items;
cout<<"Now enter cost of each item:\n";
for(i=0;i<num_of_items;i++)
{
cin>>cost[i];
sum +=cost[i]; //adding each cost to the sum
}
return sum; //returning the sum
}
};
int main()
{
OrderList o; //creatiing object of the class
double sum;
sum = o.total_cost(); //calling the member function
cout<<"The total cost is: "<<sum;
return 0;
}
OUTPUT: