Friday, December 27, 2013

Assignment 10: Constructor and Destructor SOLUTION

solution of question 1 

A common place to buy candy is from a machine. The machine sells candies, chips, gum, and cookies. You have been asked to write a program for this candy machine.
The program should do the following:
1. Show the customer the different products sold by the candy machine.
2. Let the customer make the selection.
3. Show the customer the cost of the item selected.
4. Accept money from the customer.
5. Release the item.

//************************************************************
// class cashRegister 
// This class specifies the members to implement a cash register.
//************************************************************

class cashRegister
{
    private:
 int cashOnHand; 
    public:
 cashRegister(); //Constructor Sets the cash in the register to a default amount.
 cashRegister(int cashIn); //Constructor Sets the cash in the register to a specific amount.
 int getCurrentBalance(); //The value of cashOnHand is returned.
 void acceptAmount(int amountIn);//Function to receive the amount deposited by the customer  
                                          //and update amount in the register.
};

//************************************************************
// class dispenserType
// This class specifies the members to implement a dispenser.
//************************************************************

class dispenserType
{
   private:
 int numberOfItems; //variable to store the number of items in the dispenser
 int cost; //variable to store the cost of an item
   public:
 dispenserType(); //Constructor Sets the cost and number of items in the dispenser to the default
 dispenserType(int setNoOfItems, int setCost); //Constructor Sets to the values specified
 int getNoOfItems(); //The value of numberOfItems is returned.
 int getCost(); //Function to show the cost of the item. The value of cost is returned.
 void makeSale(); //Function to reduce the number of items by 1.
};


cashRegister::cashRegister()
{
 cashOnHand = 500;
}

cashRegister::cashRegister(int cashIn)
{
 cashOnHand = cashIn;
}

int cashRegister::getCurrentBalance()
{
 return cashOnHand;
}

void cashRegister::acceptAmount(int amountIn)
{

 cashOnHand = cashOnHand + amountIn;
}

dispenserType::dispenserType()
{
 numberOfItems = 50;
 cost = 50;
}

dispenserType::dispenserType(int setNoOfItems, int setCost)
{
 numberOfItems = setNoOfItems;
 cost = setCost;
}

int dispenserType::getNoOfItems()
{
 return numberOfItems;
}

int dispenserType::getCost()
{
 return cost;
}

void dispenserType::makeSale()
{
 numberOfItems--;
}


//*****************************************************
// This program uses the classes cashRegister and
// dispenserType to implement a candy machine.
// ****************************************************

#include <iostream.h>

void showSelection();
void sellProduct(dispenserType& product, cashRegister& pCounter);
int main()
{
 cashRegister counter;
 dispenserType candy(100, 50);
 dispenserType chips(100, 65);
 dispenserType gum(75, 45);
 dispenserType cookies(50, 85);
 int choice;
 showSelection();
 cin >> choice;
 while (choice != 5)
 {
  switch (choice)
  {
   case 1:
    sellProduct(candy, counter);
    break;
   case 2:
    sellProduct(chips, counter);
    break;
   case 3:
    sellProduct(gum, counter);
    break;
   case 4:
    sellProduct(cookies, counter);
    break;
   default:
    cout << "Invalid selection." << endl;
  }
  showSelection();
  cin >> choice;
 } 
 return 0;
}

void showSelection()
{
 cout << "*** Welcome to Candy Shop ***" << endl;
 cout << "To select an item, enter " << endl;
 cout << "1 for Candy" << endl;
 cout << "2 for Chips" << endl;
 cout << "3 for Gum" << endl;
 cout << "4 for Cookies" << endl;
 cout << "5 to exit" << endl;
}

void sellProduct(dispenserType& product, cashRegister& pCounter)
{
 int amount; //variable to hold the amount entered
 int amount2; //variable to hold the extra amount needed
 if (product.getNoOfItems() > 0) //if the dispenser is not empty
 {
  cout << "Please deposit " << product.getCost() << " cents" << endl;
  cin >> amount;
  if (amount < product.getCost())
  {
   cout << "Please deposit another " << product.getCost()- amount << " cents" << endl;
   cin >> amount2;
   amount = amount + amount2;
  }
  
  if (amount >= product.getCost())
  {
   pCounter.acceptAmount(amount);
   product.makeSale();
   cout << "Collect your item at the bottom and " << "enjoy." << endl;
  }

  else
   cout << "The amount is not enough. " << "Collect what you deposited." << endl;
  cout << "*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*" << endl << endl;
 }
 else
  cout << "Sorry, this item is sold out." << endl;
}

Assignment 10: Constructor and Destructor

1
A common place to buy candy is from a machine. The machine sells candies, chips, gum, and cookies. You have been asked to write a program for this candy machine.
The program should do the following:
1. Show the customer the different products sold by the candy machine.
2. Let the customer make the selection.
3. Show the customer the cost of the item selected.
4. Accept money from the customer.
5. Release the item.
The machine has two main components: a built-in cash register and several dispensers to hold and release the products.
Define class cashRegister in C++ with the following descriptions :
Private Members:cashOnHand of type integer
Public Members:A default constructor cashRegister() sets the cash in the register to 500.
A constructor cashRegister(int) sets the cash in the register to a specific amount.
A function getCurrentBalance() which returns value of cashOnHand
A function acceptAmount(int) to receive the amount deposited by the customer and update the amount in the register
Define class dispenserType in C++ with the following descriptions :
Private Members:numberOfItems of type integer
cost of type integer
Public Members:A default constructor dispenserType () sets the cost and number of items in the dispenser to 50 each.
A constructor dispenserType (int,int) sets the cost and number of items in the dispenser to the values specified by the user.
A function getNoOfItems() to return the value of numberOfItems.
A function getCost() to return the value of cost.
A function makeSale() to reduce the number of items by 1.
When the program executes, it must do the following:
1. Show the different products sold by the candy machine.
2. Show how to select a particular product.
Once the user has made the appropriate selection, the candy machine must act accordingly. If the user has opted to buy a product and that product is available, the candy machine should show the cost of the product and ask the user to deposit the money. If the amount deposited is at least the cost of the item, the candy machine should sell the item and display an appropriate message.
Divide this program into three functions: showSelection, sellProduct, and main.
The function sellProduct must have access to the dispenser holding the product (to decrement the number of items in the dispenser by 1 and to show the cost of the item) as well as the cash register (to update the cash). Therefore, this function has two parameters: one corresponding to the dispenser and the other corresponding to the cash register.solution

Assignment 9.2: Class and Object Set 2 SOLUTION

Class and Objects
[SET – 2]

1
Write the definition for a class called Rectangle that has floating point data members length and width. The class has the following member functions:
void setlength(float) to set the length data member
void setwidth(float) to set the width data member
float perimeter() to calculate and return the perimeter of the rectangle
float area() to calculate and return the area of the rectangle
void show() to display the length and width of the rectangle
int sameArea(Rectangle) that has one parameter of type Rectangle. sameArea returns 1 if the two Rectangles have the same area, and returns 0 if they don't.
1. Write the definitions for each of the above member functions.
2. Write main function to create two rectangle objects. Set the length and width of the first rectangle to 5 and 2.5. Set the length     and width of the second rectangle to 5 and 18.9. Display each rectangle and its area and perimeter.
3. Check whether the two Rectangles have the same area and print a message indicating the result. Set the length and width of the     first rectangle to 15 and 6.3. Display each Rectangle and its area and perimeter again. Again, check whether the two     Rectangles have the same area and print a message indicating the result. 
#include<iostream.h>
#include<conio.h>


class Rectangle
{
 private:
  float length;
  float width;
 public:
  void setlength(float);
  void setwidth(float);
  float perimeter();
  float area();
  void show();
  int sameArea(Rectangle);
};


void Rectangle::setlength(float len)
{
 length = len;
}

void Rectangle::setwidth(float wid)
{
 width = wid;
}

float Rectangle::perimeter()
{
 return (2 * length + 2 * width);
}

float Rectangle::area()
{
 return length * width;
}

void Rectangle::show()
{
 cout << "Length: " << length << " Width: " << width;
}

int Rectangle::sameArea(Rectangle other)
{
 float areaf = length * width;
 float areas = other.length * other.width;
 if (areaf == areas)
  return 1;
 return 0;
}

int main()
{
 Rectangle first;
 Rectangle second;
 first.setlength(5);
 first.setwidth(2.5);
 second.setlength(5);
 second.setwidth(18.9);
 cout << "First rectangle: ";
 first.show();
 cout << endl << "Area: " << first.area() << "Perimeter: " << first.perimeter() << endl << endl;
 cout << "Second rectangle: ";
 second.show();
 cout << endl << "Area: " << second.area() << "Perimeter: " << second.perimeter() << endl << endl;
 if (first.sameArea(second))
  cout << "Rectangles have the same area\n";
 else
  cout << "Rectangles do not have the same area\n";
 first.setlength(15);
 first.setwidth(6.3);
 cout << "First rectangle: ";
 first.show();
 cout << endl << "Area: " << first.area() << "Perimeter: "<< first.perimeter() << endl << endl;
 cout << "Second rectangle: ";
 second.show();
 cout << endl << "Area: " << second.area() << "Perimeter: "<< second.perimeter() << endl << endl;
 if (first.sameArea(second))
  cout << "Rectangles have the same area\n";
 else
  cout << "Rectangles do not have the same area\n";
 getch();
 return 0;
}


2
Write the definition for a class called complex that has floating point data members for storing real and imaginary parts. The class has the following member functions:
void set(float, float) to set the specified value in object
void disp() to display complex number object
complex sum(complex) to sum two complex numbers & return complex number
1. Write the definitions for each of the above member functions.
2. Write main function to create three complex number objects. Set the value in two objects and call sum() to calculate sum and assign it in third object. Display all complex numbers. 
#include<iostream.h>
#include<conio.h>


class complex
{
   private:
 float x;
 float y;
   public:
 void set(float real, float img)
 {
  x=real; y=img;
 }
 complex sum(complex);
 void disp();
};

complex complex::sum(complex C)
{
 complex t;
 t.x = x + C.x;
 t.y = y + C.y;
 return t;
}

void complex::disp()
{
 cout<<x<<" + j"<<y<<endl;
}


int main()
{
 complex C1,C2,C3;

 C1.set(2.5,7.1);
 C2.set(4.2,5.5);
 C3=C1.sum(C2);

 cout<<"\n complex Number 1 = ";C1.disp();
 cout<<"\n complex Number 2 = ";C2.disp();
 cout<<"\n complex Number 3 = ";C3.disp();

 getch();
 return 0;
}


3
Write the definition for a class called Distance that has data member feet as integer  and inches as float. The class has the following member functions:
void set(int, float) to give value to object
void disp() to display distance in feet and inches
Distance add(Distance) to sum two distances & return distance
1. Write the definitions for each of the above member functions.
2. Write main function to create three Distance objects. Set the value in two objects and call add() to calculate sum and assign it in third object. Display all distances. 
#include<iostream.h>
#include<conio.h>


class Distance
{
   private:
 int feet;
 float inches;
   public:
 void setdist(int ft, float in)
 {
  feet=ft; inches=in;
 }
 Distance add(Distance);
 void disp();
};

Distance Distance::add(Distance D)
{
 Distance t;
 t.inches=inches + D.inches;
 t.feet =0;
 if(t.inches>=12.0)
 {
  t.inches-=12.0;
  t.feet++;
 }
 t.feet +=feet + D.feet;
 return t;
}

void Distance::disp()
{
 cout<<feet<<"\'"<<inches<<"\" ";
}


int main()
{
 Distance d1,d2,d3;
 d1.setdist(10,7.1);
 d2.setdist(23,5.5);
 d3=d1.add(d2);

 cout<<"\n distance 1 = ";d1.disp();
 cout<<"\n distance 2 = ";d2.disp();
 cout<<"\n distance 3 = ";d3.disp();

 getch();
 return 0;
}


4
Write the definition for a class called time that has hours and minutes as integer. The class has the following member functions:
void settime(int, int) to set the specified value in object
void showtime() to display time object
time sum(time) to sum two time object & return time
1. Write the definitions for each of the above member functions.
2. Write main function to create three time objects. Set the value in two objects and call sum() to calculate sum and assign it in third object. Display all time objects. 
#include<iostream.h>
#include<conio.h>


class time
{
   private:
 int hours;
 int minutes;
   public:
 void settime(int h, int m)
 {
  hours=h; minutes=m;
 }
 time sum(time);
 void showtime();
};

time time::sum(time TM)
{
 time t;
 t.minutes = minutes + TM.minutes;
 t.hours=t.minutes/60;
 t.minutes=t.minutes%60;
 t.hours += hours + TM.hours;
 return t;
}

void time::showtime()
{
 cout<<hours<<" hours and "<<minutes<<" minutes"<<endl;
}


int main()
{
 time T1,T2,T3;
 T1.settime(2,45);
 T2.settime(3,30);
 T3=T1.sum(T2);

 cout<<"\n Time 1 : ";T1.showtime();
 cout<<"\n Time 2 : ";T2.showtime();
 cout<<"\n Time 3 : ";T3.showtime();

 getch();
 return 0;
}

Assignment 9.2: Class and Object Set 2

Class and Objects
[SET – 2]

1
Write the definition for a class called Rectangle that has floating point data members length and width. The class has the following member functions:
void setlength(float) to set the length data member
void setwidth(float) to set the width data member
float perimeter() to calculate and return the perimeter of the rectangle
float area() to calculate and return the area of the rectangle
void show() to display the length and width of the rectangle
int sameArea(Rectangle) that has one parameter of type Rectangle. sameArea returns 1 if the two Rectangles have the same area, and returns 0 if they don't.
1. Write the definitions for each of the above member functions.
2. Write main function to create two rectangle objects. Set the length and width of the first rectangle to 5 and 2.5. Set the length     and width of the second rectangle to 5 and 18.9. Display each rectangle and its area and perimeter.
3. Check whether the two Rectangles have the same area and print a message indicating the result. Set the length and width of the     first rectangle to 15 and 6.3. Display each Rectangle and its area and perimeter again. Again, check whether the two     Rectangles have the same area and print a message indicating the result. solution

2
Write the definition for a class called complex that has floating point data members for storing real and imaginary parts. The class has the following member functions:
void set(float, float) to set the specified value in object
void disp() to display complex number object
complex sum(complex) to sum two complex numbers & return complex number
1. Write the definitions for each of the above member functions.
2. Write main function to create three complex number objects. Set the value in two objects and call sum() to calculate sum and assign it in third object. Display all complex numbers. solution

3
Write the definition for a class called Distance that has data member feet as integer  and inches as float. The class has the following member functions:
void set(int, float) to give value to object
void disp() to display distance in feet and inches
Distance add(Distance) to sum two distances & return distance
1. Write the definitions for each of the above member functions.
2. Write main function to create three Distance objects. Set the value in two objects and call add() to calculate sum and assign it in third object. Display all distances. solution

4
Write the definition for a class called time that has hours and minutes as integer. The class has the following member functions:
void settime(int, int) to set the specified value in object
void showtime() to display time object
time sum(time) to sum two time object & return time
1. Write the definitions for each of the above member functions.
2. Write main function to create three time objects. Set the value in two objects and call sum() to calculate sum and assign it in third object. Display all time objects. solution

Assignment 9.1: Class and Object Set 1 SOLUTION

Class and Object
[SET – 1]

1
Define a class student with the following specification
Private members of class student
admno                        integer
sname                        20 character
eng. math, science       float
total                            float
ctotal()                        a function to calculate eng + math + science with float return type.
Public member function of class student
Takedata()                   Function to accept values for admno, sname, eng, science and invoke ctotal() to                                    calculate total.
Showdata()                   Function to display all the data members on the screen. 
#include<iostream.h>
#include<conio.h>
#include<stdio.h>


class student
{
private:
 int admno;
 char sname[20];
 float eng,math,science;
 float total;
 float ctotal()
 {
  return eng+math+science;
 }
public:
 void Takedata()
 {
  cout<<"Enter admission number ";
  cin>> admno;
  cout<<"Enter student name " ;
  gets(sname);
  cout<< "Enter marks in english, math, science ";
  cin>>eng>>math>>science;
  total=ctotal();
 }

 void Showdata()
 {
  cout<<"Admission number "<<admno<<"\nStudent name "<<sname<<"\nEnglish "
   <<eng<<"\nMath "<<math<<"\nScience "<<science<<"\nTotal "<<total;
 }
};

int main ()
{
 clrscr();
 student obj ;
 obj.Takedata();
 obj.Showdata();
 getch();
 return 0;
}




2
 Define a class batsman with the following specifications:
Private members:
bcode                            4 digits code number
bname                           20 characters
innings, notout, runs        integer type
batavg                           it is calculated according to the formula – 
                                     batavg =runs/(innings-notout)
calcavg()                        Function to compute batavg
Public members:
readdata()                      Function to accept value from bcode, name, innings, notout and invoke the function                                       calcavg()
displaydata()                   Function to display the data members on the screen. solution
#include<iostream.h>
#include<conio.h>
#include<stdio.h>

class batsman
{
 int bcode;
 char bname[20];
 int innings,notout,runs;
 int batavg;
 void calcavg()
 {
  batavg=runs/(innings-notout);
 }

public :
 void readdata ();
 void displaydata();
};

void batsman::readdata ()
{
 cout<<"Enter batsman code ";
 cin>> bcode;
 cout<<"Enter batsman name ";
 gets(bname);
 cout<<"enter innings,notout and runs ";
 cin>>innings>>notout>>runs;
 calcavg();
}

void batsman::displaydata()
{
 cout<<"Batsman code "<<bcode<<"\nBatsman name "<<bname<<"\nInnings "<<innings
 <<"\nNot out "<<notout<<"\nRuns "<<runs<<"\nBatting Average "<<batavg;
}


int main()
{
 batsman obj;
 obj.readdata();
 obj.displaydata();
 getch();
 return 0;
}



3
Define a class TEST in C++ with following description:
Private Members
TestCode of type integer
Description of type string
NoCandidate of type integer
CenterReqd (number of centers required) of type integer
A member function CALCNTR() to calculate and return the number of centers as
(NoCandidates/100+1)
Public Members 
-  A function SCHEDULE() to allow user to enter values for TestCode, Description, NoCandidate & call function CALCNTR() to calculate the number of Centres
- A function DISPTEST() to allow user to view the content of all the data members 
#include<iostream.h>
#include<conio.h>
#include<stdio.h>

class TEST
{
  private:
 int TestCode;
 char Description[30];
 int NoCandidate;
 int CenterReqd;
 int CALCNTR()
 {
  return NoCandidate/100+1;
 }
  public:
 void SCHDULE();
 void DISPTEST();
};

void TEST::SCHDULE()
{
 cout<<"Enter Test code ";
 cin>> TestCode;
 cout<<"Enter description ";
 gets(Description);
 cout<< "Enter no of candidates ";
 cin>>NoCandidate;
 CenterReqd=CALCNTR();
}

void TEST :: DISPTEST()
{
 cout<<"Test code "<<TestCode<<"\nDescripton "<<Description<<"\nNo of candidate "
 <<NoCandidate<<"\nCenter required "<<CenterReqd;
}

int main ()
{
 TEST obj;
 obj.SCHDULE();
 obj.DISPTEST();
 getch();
 return 0;
}



4
 Define a class in C++ with following description:
Private Members
A data member Flight number of type integer
A data member Destination of type string
A data member Distance of type float
A data member Fuel of type float
A member function CALFUEL() to calculate the value of Fuel as per the following criteria
            Distance                                                          Fuel
            <=1000                                                           500
            more than 1000  and <=2000                          1100
            more than 2000                                              2200
Public Members
A function FEEDINFO() to allow user to enter values for Flight Number, Destination, Distance & call function CALFUEL() to calculate the quantity of Fuel
A function SHOWINFO() to allow user to view the content of all the data members 
#include<iostream.h>
#include<conio.h>
#include<stdio.h>

class TEST
{
  private:
 int TestCode;
 char Description[30];
 int NoCandidate;
 int CenterReqd;
 int CALCNTR()
 {
  return NoCandidate/100+1;
 }
  public:
 void SCHDULE();
 void DISPTEST();
};

void TEST::SCHDULE()
{
 cout<<"Enter Test code ";
 cin>> TestCode;
 cout<<"Enter description ";
 gets(Description);
 cout<< "Enter no of candidates ";
 cin>>NoCandidate;
 CenterReqd=CALCNTR();
}

void TEST :: DISPTEST()
{
 cout<<"Test code "<<TestCode<<"\nDescripton "<<Description<<"\nNo of candidate "
 <<NoCandidate<<"\nCenter required "<<CenterReqd;
}

int main ()
{
 TEST obj;
 obj.SCHDULE();
 obj.DISPTEST();
 getch();
 return 0;
}


5
Define a class BOOK with the following specifications :
Private members of the class BOOK are
BOOK NO                integer type
BOOKTITLE             20 characters
PRICE                     float (price per copy)
TOTAL_COST()        A function to calculate the total cost for N number of copies where N is passed to the                               function as argument. 
Public members of the class BOOK are
INPUT()                   function to read BOOK_NO. BOOKTITLE, PRICE
PURCHASE()            function to ask the user to input the number of copies to be purchased. It invokes                               TOTAL_COST() and prints the total cost to be paid by the user. 
Note : You are also required to give detailed function definitions.
#include<iostream.h>
#include<stdio.h>
#include<conio.h>

class BOOK
{
 int BOOKNO;
 char BOOKTITLE[20];
 float PRICE;
 void TOTAL_COST(int N)
 {
  float tcost;
  tcost=PRICE*N;
  cout<<tcost;
 }
public:
 void INPUT()
 {
  cout<<"Enter Book Number ";
  cin>>BOOKNO;
  cout<<"Enter Book Title ";
  gets(BOOKTITLE);
  cout<<"Enter price per copy ";
  cin>>PRICE;
 }
 
 void PURCHASE()
 {
  int n;
  cout<<"Enter number of copies to purchase ";
  cin>>n;
  cout<<"Total cost is ";
  TOTAL_COST(n);
 }
};
 
int main()
{
 BOOK obj;
 obj.INPUT();
 obj.PURCHASE();
 getch();
 return 0;
}


6
Define a class REPORT with the following specification:
Private members :
adno                         4 digit admission number
name                        20 characters
marks                       an array of 5 floating point values
average                    average marks obtained
GETAVG()                 a function to compute the average obtained in five subject
Public members:
READINFO()              function to accept values for adno, name, marks. Invoke the function GETAVG()             
DISPLAYINFO()          function to display all data members of report on the screen.
You should give function definitions. 

#include<iostream.h>
#include<stdio.h>
#include<conio.h>

class REPORT
{
 int adno;
 char name[20];
 float marks[5];
 float average;
 void GETAVG()
 {

  average = (marks[0]+marks[1]+marks[2]+marks[3]+marks[4])/5;
 }

public:
 void READINFO();
 void DISPLAYINFO();
};

void REPORT::READINFO()
{

 do
 {
  cout<<"Enter 4 digit admission number ";
  cin>>adno;
 }while(adno<999 || adno>10000);

 cout<<"Enter name";
 gets(name);
 cout<<"Enter marks in ";

 for(int i=0;i<5;i++)
 {
  cout<<"Subject "<<i+1<<":";

  cin>>marks[i];
 };

 GETAVG();
}



void REPORT::DISPLAYINFO()
{

 cout<<"Admission number:"<<adno<<" Name:"<<name<<" Marks are:"<< marks[0]<<" "<< marks[1]
 <<" "<<marks[2]<<" "<< marks[3]<<" "<< marks[4]<<" Average:"<<average;
}

int main()
{
 REPORT obj;
 obj.READINFO();
 obj.DISPLAYINFO();

 getch();
 return 0;
}