Reputation: 61
I'm still new to classes so here what i have done so far. In this program I have to prompt the user to input how many products and the prices and i have to display back again like this :
No Product Code Price
1 101 4.50
and calculate the average price.
my class have to hold up to 100 objects which I'm still not sure how o implement. Hope anyone can help me with this.
#include <iostream>
using namespace std;
class Product{
private :
int code;
double price;
public :
Product ();
void setCode(int);
void setPrice(double);
int getCode();
double getPrice();
};
Product :: Product()
{
code = 0;
price = 0;
}
void Product :: setCode(int c)
{
code = c;
}
void Product :: setPrice(double p)
{
price = p;
}
int Product :: getCode()
{
return code;
}
double Product :: getPrice()
{
return price;
}
int main(){
const int size = 100;
Product m[size];
int procode;
double proprice;
int num;
double sum= 0;
cout << "How many products to enter? ";
cin >> num;
cout << endl;
for(int i=0; i<num ;i++)
{
cout << "Enter the information of product #"<< (i+1)<<endl;
int code;
cout << "\tProduct Code: ";
cin >> code;
m[i].setCode( code );
double price;
cout << "\tPrice: ";
cin >> price;
m[i].setPrice( price );
sum = sum + price;
}
///output??
cout <<"No"<<" "<<"Product Code"<<" "<<"Price" <<endl;
cout<<" "<<m[i].getCode()<<" "<<m[i].getPrice()<<endl;
cout<<"Average: " << sum/num << endl;
return 0;
}
Upvotes: 1
Views: 121
Reputation: 1949
Did you mean dynamic allocation?
If you want to have variable amount of Products specified by user, you must create the array dynamically after you know num
.
For example:
int main() {
Product * m;
int num;
cout << "How many products to enter? ";
cin >> num;
cout << endl;
m = new Product[num];
for (int i=0; i<num; i++) {
// something with the array
}
delete [] m;
return 0;
}
Upvotes: 1
Reputation: 310980
Function main can be written the following way
int main()
{
const size_t MAX_ITEMS = 100;
Product m[MAX_ITEMS];
size_t num;
cout << "How many products to enter? ";
cin >> num;
if ( MAX_ITEMS < num ) num = MAX_ITEMS;
for ( size_t i = 0; i < num; i++ )
{
cout << "\nEnter the information of product #" << (i+1) << endl;
int code;
cout << "\tProduct Code: ";
cin >> code;
m[i].setCode( code );
double price;
cout < "\tPrice: ";
cin >> price;
m[i].setPrice( price );
}
// here can be the code for output data
return 0;
}
Upvotes: 0
Reputation: 4868
for(int i=0; i<num ;i++)
{
cout << "Enter the information of product #"<< (i+1)<<endl;
cout << "Product Code:";
cin >> procode;
m[i].setCode(procode);
cout < "\nPrice:";
cin >> proprice;
m[i].setPrice(proprice);
}
This will set required number of objects.
Access as
cout<<m[index].getCode()<<m[index].getPrice();
Upvotes: 1