# C++ solutions for : [Object-Oriented Programming in C++, Third Edition]

Printable View

Show 40 post(s) from this thread on one page
• 12-27-2006, 03:00 PM
Amahdy
CHAPTER 5FUNCTIONS code;

Code:

```/**1.  Refer to the CIRCAREA program in Chapter 2, C++ Programming Basics. Write a function   called circarea() that finds the area of a circle in a similar way. It should take an argument of type float   and return an argument of the same type. Write a main() function that gets a radius value from the   user, calls circarea(), and displays the result.*/ #include<iostream> #include<conio.h> using namespace std; float circarea(float radius); /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // circarea.cpp // demonstrates floating point variables #include <iostream>                    //for cout, etc. using namespace std; int main()   {   float rad;                          //variable of type float   const float PI = 3.14159F;          //type const float   cout << "Enter radius of circle: ";  //prompt   cin >> rad;                          //get radius   float area = PI * rad * rad;        //find area   cout << "Area is " << area << endl;  //display answer   return 0;   } ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ void main(void) {         cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";         cout<<"-------------------------------------------------------------------------------\n"<<endl;                 float rad;                 do{         cout<<"Enter radius of circle: "; cin>> rad;         cout <<"Area is "<<circarea(rad);         cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;         }while(getch()=='c'); } float circarea(float radius) { return 3.14159F*radius*radius;}```
Code:

```/**2.  Raising a number n to a power p is the same as multiplying n by itself p times. Write a function   called power() that takes a double value for n and an int value for p, and returns the result as a double   value. Use a default argument of 2 for p, so that if this argument is omitted, the number n will be   squared. Write a main() function that gets values from the user to test this function.*/ #include<iostream> #include<conio.h> using namespace std; double power(double n, int p=2); void main(void) {         cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";         cout<<"-------------------------------------------------------------------------------\n"<<endl;                 double n; int p=2;                 do{         cout<<"Enter n: "; cin>> n;         cout<<"Enter p: "; cin>> p;         cout <<"The power is "<<power(n, p);         cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;         }while(getch()=='c'); } double power(double n, int p){ for(int ret=1; p>0; p--) ret*=n; return ret;}```
Code:

```/**3.  Write a function called zeroSmaller() that is passed two int arguments by reference and then sets   the smaller of the two numbers to 0. Write a main() program to exercise this function.*/ #include<iostream> #include<conio.h> using namespace std; bool zeroSmaller(int& n1, int& n2); void main(void) {         cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";         cout<<"-------------------------------------------------------------------------------\n"<<endl;                 int n1, n2;                 do{         cout<<"Enter n1: "; cin>> n1;         cout<<"Enter n2: "; cin>> n2;         cout <<"The number assigned to zero is ";         if(zeroSmaller(n1, n2)) cout<<"n1"; else cout<<"n2";         cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;         }while(getch()=='c'); } bool zeroSmaller(int& n1, int& n2){         if(n1<n2) {n1=0; return true;}         else {n2=0;return false;}}```
Code:

```/**4.  Write a function that takes two Distance values as arguments and returns the larger one. Include   a main() program that accepts two Distance values from the user, compares them, and displays the   larger. (See the retstrc program for hints.).*/ #include<iostream> #include<conio.h> using namespace std; int distWatch(int d1, int d2); void main(void) {         cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";         cout<<"-------------------------------------------------------------------------------\n"<<endl;                 int d1, d2;                 do{         cout<<"Enter d1: "; cin>> d1;         cout<<"Enter d2: "; cin>> d2;         cout <<"The largest distance is "<<distWatch(d1, d2);         cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;         }while(getch()=='c'); } int distWatch(int d1, int d2){ if(d1<d2) return d2; else return d1;}```
Code:

```/*5.  Write a function called hms_to_secs() that takes three int valuesfor hours, minutes, and   secondsas arguments, and returns the equivalent time in seconds (type long). Create a program   that exercises this function by repeatedly obtaining a time value in hours, minutes, and seconds from   the user (format 12:59:59), calling the function, and displaying the value of seconds it returns.*/ #include<iostream> #include<conio.h> using namespace std; long hms_to_secs(int hours, int minutes, int seconds); void main(void) {         cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";         cout<<"-------------------------------------------------------------------------------\n"<<endl;                 int h, m, s; char sep;                 do{         cout<<"Enter the time in format hh:mm:ss : "; cin>>h>>sep>>m>>sep>>s;         cout <<"The equivalent time in seconds is : "<<hms_to_secs(h, m, s);         cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;         }while(getch()=='c'); } long hms_to_secs(int hours, int minutes, int seconds){ return seconds+minutes*60+hours*3600;}```
• 12-27-2006, 03:02 PM
Amahdy
Code:

```/*6.  Start with the program from Exercise 11, Chapter 4, Structures, which adds two struct time   values. Keep the same functionality, but modify the program so that it uses two functions. The first,   time_to_secs(), takes as its only argument a structure of type time, and returns the equivalent in   seconds (type long). The second function, secs_to_time(), takes as its only argument a time in   seconds (type long), and returns a structure of type time. */ #include<iostream> #include<conio.h> using namespace std; struct time{int hours; int minutes; int seconds;}; long time_to_secs(time t); time secs_to_time(long s); void main(void) {         cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";         cout<<"-------------------------------------------------------------------------------\n"<<endl;                 time t1, t2, t3; char c;                 do{         cout<<"In [hh:mm:ss] format;\n";         cout<<"Enter first time value : "; cin >>t1.hours>>c>>t1.minutes>>c>>t1.seconds;         cout<<"Enter second time value: "; cin >>t2.hours>>c>>t2.minutes>>c>>t2.seconds;         t3=secs_to_time(time_to_secs(t1)+time_to_secs(t2));         cout<<"The result is: "<<t3.hours<<":"<<t3.minutes<<":"<<t3.seconds;         cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;         }while(getch()=='c'); } long time_to_secs(time t){ return t.hours*3600+t.minutes*60+t.seconds;} time secs_to_time(long s){         time t;         t.seconds=s%60; t.minutes=((s-t.seconds)%3600)/60; t.hours=s/3600;         if(t.seconds>59) {t.seconds-=59; t.minutes++;} //Check seconds over.         if(t.minutes>59) {t.minutes-=59; t.hours++;}  //Check minutes over.         return t; }```
Code:

```/*7.  Start with the power () function of Exercise 2, which works only with type double. Create a series   of overloaded functions with the same name that, in addition to double, also work with types char,   int, long, and float. Write a main() program that exercises these overloaded functions with all   argument types.*/ #include<iostream> #include<conio.h> using namespace std; double power(double n, int p=2); char  power(char  n, int p=2); int    power(int    n, int p=2); long  power(long  n, int p=2); float  power(float  n, int p=2); void main(void) {         cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";         cout<<"-------------------------------------------------------------------------------\n"<<endl;                 char sep; int p=2; double d_n; char c_n; int i_n; long l_n; float f_n;                 do{         cout<<"In [n^p] format;\n";         cout<<"Enter a double type n : "; cin >>d_n>>sep>>p;         cout<<"The power is "<<power(d_n, p)<<endl;         cout<<"Enter a char type n  : "; cin >>c_n>>sep>>p;         cout<<"The power is "<<power(c_n, p)<<endl;         cout<<"Enter a int type n    : "; cin >>i_n>>sep>>p;         cout<<"The power is "<<power(i_n, p)<<endl;         cout<<"Enter a long type n  : "; cin >>l_n>>sep>>p;         cout<<"The power is "<<power(l_n, p)<<endl;         cout<<"Enter a float type n  : "; cin >>f_n>>sep>>p;         cout<<"The power is "<<power(f_n, p)<<endl;         cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;         }while(getch()=='c'); } double power(double n, int p){ for(int ret=1; p>0; p--) ret*=n; return ret;} char  power(char  n, int p){ for(int ret=1; p>0; p--) ret*=n; return ret;} int    power(int    n, int p){ for(int ret=1; p>0; p--) ret*=n; return ret;} long  power(long  n, int p){ for(int ret=1; p>0; p--) ret*=n; return ret;} float  power(float  n, int p){ for(int ret=1; p>0; p--) ret*=n; return ret;}```
Code:

```/*8.  Write a function called swap() that interchanges two int values passed to it by the calling program.   (Note that this function swaps the values of the variables in the calling program, not those in the   function.) Youll need to decide how to pass the arguments. Create a main() program to exercise the   function.*/ #include<iostream> #include<conio.h> using namespace std; void swap(int& a, int& b); void main(void) {         cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";         cout<<"-------------------------------------------------------------------------------\n"<<endl;                 int a, b;                 do{         cout<<"Enter a : "; cin >>a;         cout<<"Enter b : "; cin >>b; swap(a, b);         cout<<"Now a value is : "<<a<<" and b value is : "<<b;         cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;         }while(getch()=='c'); } void swap(int& a, int& b){int c=a; a=b; b=c;}```
Code:

```/*9.  This exercise is similar to Exercise 8, except that instead of two int variables, have the swap()   function interchange two struct time values (see Exercise 6).*/ #include<iostream> #include<conio.h> using namespace std; struct time{int hours; int minutes; int seconds;}; void swap(time& t1, time& t2); void main(void) {         cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";         cout<<"-------------------------------------------------------------------------------\n"<<endl;                 time t1, t2; char c;                 do{         cout<<"In [hh:mm:ss] format;\n";         cout<<"Enter first time value : "; cin >>t1.hours>>c>>t1.minutes>>c>>t1.seconds;         cout<<"Enter second time value: "; cin >>t2.hours>>c>>t2.minutes>>c>>t2.seconds;         swap(t1, t2);         cout<<"Now first time is : "  <<t1.hours<<c<<t1.minutes<<c<<t1.seconds                 <<" and second time is : "<<t2.hours<<c<<t2.minutes<<c<<t2.seconds;         cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;         }while(getch()=='c'); } void swap(time& a, time& b){time c=a; a=b; b=c;}```
Code:

```/*10.  Write a function that, when you call it, displays a message telling how many times it has been   called: I have been called 3 times, or whatever. Write a main() program that calls this function at   least 10 times. Try implementing this function in two different ways. First, use an external variable to   store the count. Second, use a local static variable. Which is more appropriate? Why cant you use   an automatic variable?*/ #include<iostream> #include<conio.h> using namespace std; void caller_counter(void); void main(void) {         cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";         cout<<"-------------------------------------------------------------------------------\n"<<endl;                 int outer_counter=0;                 do{         outer_counter++; caller_counter();         cout<<"\nThe main programme counter value is: "<<outer_counter;         cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;         }while(getch()=='c'); } void caller_counter(void){         //I can't use an automatic variable coz it's created once I call the function only.         static int inner_counter=0; inner_counter++;         cout<<"I have been called "<<inner_counter<<" times";}```
• 12-27-2006, 03:03 PM
Amahdy
Code:

```/*11.  Write a program, based on the sterling structure of Exercise 10 in Chapter 4, Structures, that   obtains from the user two money amounts in old-style British format (£9:19:11), adds them, and   displays the result, again in old-style format. Use three functions. The first should obtain a pounds-   shillings-pence value from the user and return the value as a structure of type sterling. The second   should take two arguments of type sterling and return a value of the same type, which is the sum of   the arguments. The third should take a sterling structure as its argument and display its value.*/ #include<iostream> #include<conio.h> using namespace std; struct sterling{int pounds; int shillings; int pence;}; sterling psp_to_sterling(int pounds, int shillings, int pence); sterling sterling_add(sterling s1, sterling s2); void sterling_disp(sterling s); char c; void main(void) {         cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";         cout<<"-------------------------------------------------------------------------------\n"<<endl;                 int x, y, z; sterling x1, x2;                 do{         cout<<"In [9:19:11] format;\n";         cout<<"Enter first money amount in old-style British  : \x9c";         cin>>x>>c>>y>>c>>z; x1=psp_to_sterling(x, y, z);         cout<<"Enter second money amount in old-style British : \x9c";         cin>>x>>c>>y>>c>>z; x2=psp_to_sterling(x, y, z);         sterling_disp(sterling_add(x1, x2));         cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;         }while(getch()=='c'); } sterling psp_to_sterling(int pounds, int shillings, int pence){         sterling x;        x.pounds=pounds; x.shillings=shillings; x.pence=pence; return x;} sterling sterling_add(sterling s1, sterling s2){         s1.pounds += s2.pounds; s1.shillings += s2.shillings; s1.pence += s2.pence;         if(s1.pence>11){s1.shillings += static_cast<int>(s1.pence/12); s1.pence %= 12;}         if(s1.shillings>19){s1.pounds += static_cast<int>(s1.shillings/20); s1.shillings %= 20;}         return s1;}         void sterling_disp(sterling s){         cout<<"Total is                                      : \x9c"                 <<s.pounds<<c<<s.shillings<<c<<s.pence;}```
Code:

```/*12.  Revise the four-function fraction calculator from Exercise 12, Chapter 4, so that it uses   functions for each of the four arithmetic operations. They can be called fadd(), fsub(), fmul(), and fdiv   (). Each of these functions should take two arguments of type struct fraction, and return an argument   of the same type.*/ #include<iostream> #include<conio.h> using namespace std; struct fraction{int numerator; int denominator;}; fraction fadd(fraction a, fraction b); fraction fsub(fraction a, fraction b); fraction fmul(fraction a, fraction b); fraction fdiv(fraction a, fraction b); void main(void) {         cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";         cout<<"-------------------------------------------------------------------------------\n"<<endl;                 fraction f; char c, op;                 do{         cout<<"Enter your task : ";         cin >>f.numerator>>c>>f.denominator>>op>>f.numerator>>c>>f.denominator;         if(!f.denominator || !f.denominator) {cout<<"Illeagle fraction !"<<endl; op=false;}         switch(op) {         case '+':        f=fadd(f, f); break;         case '-':        f=fsub(f, f); break;         case '*':        f=fmul(f, f); break;         case '/':        f=fdiv(f, f); break;         default:        cout<<"Unknow operator please try again !"<<endl;}         cout<<"Answer = "<<f.numerator<<c<<f.denominator;         cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;         }while(getch()=='c'); } fraction fadd(fraction a, fraction b){         fraction f;         f.numerator  =a.numerator*b.denominator+a.denominator*b.numerator;         f.denominator=a.denominator*b.denominator; return f;} fraction fsub(fraction a, fraction b){         fraction f;         f.numerator  =a.numerator*b.denominator-a.denominator*b.numerator;         f.denominator=a.denominator*b.denominator; return f;} fraction fmul(fraction a, fraction b){         fraction f;         f.numerator  =a.numerator*b.numerator;         f.denominator=a.denominator*b.denominator; return f;} fraction fdiv(fraction a, fraction b){         fraction f;         if(b.numerator != 0){         f.numerator  =a.numerator*b.denominator;         f.denominator=b.numerator*a.denominator;}         else              cout<<"Math error !"<<endl; return f;}```
• 12-27-2006, 03:05 PM
Amahdy
CHAPTER 6OBJECTS AND CLASSES

Quote:

Questions:
----------
1. What is the purpose of a class declaration?
2. A ________ has the same relation to an ________ that a basic data type has to a variable of that type.
3. In a class declaration, data or functions designated private are accessible
a. to any function in the program.
b. only if you know the password.
c. to member functions of that class.
d. only to public members of the class.
4. Write a class declaration that creates a class called leverage with one private data member, crowbar, of type int and one public function whose declaration is void pry().
5. True or false: Data items in a class must be private.
6. Write a statement that defines an object called lever1 of the leverage class described in Question 4.
7. The dot operator (or class member access operator) connects the following two entities (reading from left to right):
a. A class member and a class object
b. A class object and a class
c. A class and a member of that class
d. A class object and a member of that class
8. Write a statement that executes the pry() function in the lever1 object, as described in Questions 4 and 6.
9. Member functions defined inside a class declaration are ________ by default.
10. Write a member function called getcrow() for the leverage class described in Question 4. This function should return the value of the crowbar data. Assume the function is defined within the class declaration.
11. A constructor is executed automatically when an object is ________.
12. A constructors name is the same as _________.
13. Write a constructor that initializes to 0 the crowbar data, a member of the leverage class described in Question 4. Assume the constructor is defined within the class declaration.
14. True or false: In a class you can have more than one constructor with the same name.
15. A member function can always access the data
a. in the object of which it is a member.
b. in the class of which it is a member.
c. in any object of the class of which it is a member.
d. in the public part of its class.
16. Assume the member function getcrow() described in Question 10 is defined outside the class declaration. Write the declaration that goes inside the class declaration.
17. Write a revised version of the getcrow() member function from Question 10 that is defined outside the class declaration.
18. The only technical difference between structures and classes in C++ is that _________.
19. If three objects of a class are defined, how many copies of that classs data items are stored in memory? How many copies of its member functions?
20. Sending a message to an object is the same as _________.
21. Classes are useful because they
a. are removed from memory when not in use.
b. permit data to be hidden from other classes.
c. bring together all aspects of an entity in one place.
d. can closely model objects in the real world.
22. True or false: There is a simple but precise methodology for dividing a realworld programming problem into classes.
23. For the object for which it was called, a const member function
a. can modify both const and nonconst member data.
b. can modify only const member data.
c. can modify only nonconst member data.
d. can modify neither const nor nonconst member data.
24. True or false: If you declare a const object, it can only be used with const member functions.
25. Write a declaration (not a definition) for a const void function called aFunc() that takes one const argument called jerry of type float.
__________
Quote:

My answers:
-----------
1. Manage objects formation.
2. Class, Object.
3. to member functions of that class.
4. class leverage{int crowbar; public: void pry();};
5. False.
6. leverage lever1;
7. A class object and a member of that class.
8. lever1.pry();
9. private.
10. int getcrow(){ return crowbar;}
11. defined.
12. class.
13. levrage(): crowbar(0){}
14. True.
15. in the object of which it is a member.
16. int getcrow();
17. int leverage::getcrow(){ return crowbar;}
18. members are by default public in struct, and private in class.
19. 3, 1.
20. passing to a function.
21. permit data to be hidden from other classes, bring together all aspects of an entity in one place, can closely model objects in the real world.
22. True.
23. can modify neither const nor nonconst member data.
24. False.
25. void aFunc(const float jerry) const;
___________
Quote:

Answers:
--------
1. A class declaration describes how objects of a class will look when they are created.
2. class, object
3. c
4.
class leverage
{
private:
int crowbar;
public:
void pry();
};

5. False; both data and functions can be private or public.
6. leverage lever1;
7. d
8. lever1.pry();
9. inline (also private)
10.
int getcrow()
{ return crowbar; }

11. created (defined)
12. the class of which it is a member
13.
leverage()
{ crowbar = 0; }

14. True
15. a
16. int getcrow();
17.
int leverage::getcrow()
{ return crowbar; }

18. member functions and data are, by default, public in structures but private in classes
19. three, one
20. calling one of its member functions
21. b, c, d
22. False; trial and error may be necessary.
23. d
24. True
25. void aFunc(const float jerry) const;
________
• 12-27-2006, 03:07 PM
Amahdy
CHAPTER 6OBJECTS AND CLASSES codes;

Code:

```/**1.  Create a class that imitates part of the functionality of the basic data type int.Call the class Int   (note different spelling). The only data in this class is an int variable. Include member functions to   initialize an Int to 0, to initialize it to an int value, to display it (it looks just like an int), and to add two   Int values.   Write a program that exercises this class by creating two initialized and one uninitialized Int values,   adding these two initialized values and placing the response in the uninitialized value, and then   displaying this result.*/ #include<iostream> #include<conio.h> using namespace std; class Int{         int int_var; public:         Int(): int_var(0){}         Int(int begin): int_var(begin){}         void display() const{ cout<<int_var;}         void add(Int x, Int y){ int_var=x.int_var+y.int_var;} }; void main(void) {         cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";         cout<<"-------------------------------------------------------------------------------\n"<<endl;                 Int a=5, b=7, c;                 do{         c.add(a,b);         c.display();         cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;         }while(getch()=='c'); }```
Code:

```/**2.  Imagine a tollbooth at a bridge. Cars passing by the booth are expected to pay a 50 cent toll.   Mostly they do, but sometimes a car goes by without paying. The tollbooth keeps track of the   number of cars that have gone by, and of the total amount of money collected.   Model this tollbooth with a class called tollBooth. The two data items are a type unsigned int to hold   the total number of cars, and a type double to hold the total amount of money collected. A   constructor initializes both of these to 0. A member function called payingCar() increments the car   total and adds 0.50 to the cash total. Another function, called nopayCar(), increments the car total   but adds nothing to the cash total. Finally, a member function called display() displays the two totals.   Make appropriate member functions const.   Include a program to test this class. This program should allow the user to push one key to count a   paying car, and another to count a nonpaying car. Pushing the [Escape] key should cause the   program to print out the total cars and total cash and then exit. */ #include<iostream> #include<conio.h> using namespace std; class tollBooth{         unsigned int num_cars;         double money_amount; public:         tollBooth(): num_cars(0), money_amount(0) {}         void payingCar(){ num_cars++; money_amount+=.5;}         void nopayCar(){ num_cars++;}         void display() const {                 cout<<"\rTotal number of cars is: "<<num_cars;                 cout<<"\nTotal money amount is  : "<<money_amount;} }; void main(void) {         cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";         cout<<"-------------------------------------------------------------------------------\n"<<endl;                 tollBooth x;                 do{                 for(;;){                 switch(toupper(getch())){                 case('P'): x.payingCar(); cout<<"\rPayed";  break;                 case('N'): x.nopayCar(); cout<<"\rNot payed"; break;                 case(27 ): x.display(); goto end;}                 } end:         cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;         }while(getch()=='c'); }```
Code:

```/**3.  Create a class called time that has separate int member data for hours, minutes, and seconds.   One constructor should initialize this data to 0, and another should initialize it to fixed values.   Another member function should display it, in 11:59:59 format. The final member function should   add two objects of type time passed as arguments.   A main() program should create two initialized time objects (should they be const?) and one that isnt   initialized. Then it should add the two initialized values together, leaving the result in the third time   variable. Finally it should display the value of this third variable. Make appropriate member   functions const.  */ #include<iostream> #include<conio.h> using namespace std; class time{         int hours, minutes, seconds; public:         time(): hours(0), minutes(0), seconds(0) {}         time(int h, int m, int s): hours(h), minutes(m), seconds(s) {}         void display() const { cout<<hours<<":"<<minutes<<":"<<seconds;}         void add(time x, time y){         long tmp;         tmp=x.hours*3600+x.minutes*60+x.seconds+y.hours*3600+y.minutes*60+y.seconds;         seconds=tmp%60; minutes=((tmp-seconds)%3600)/60; hours=tmp/3600;         if(seconds>59) {seconds-=59; minutes++;}         if(minutes>59) {minutes-=59; hours++;}}}; void main(void) {         cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";         cout<<"-------------------------------------------------------------------------------\n"<<endl;                 const time t1(12, 34, 4), t2(3, 34, 45);         time t3;                 do{         t3.add(t1, t2);         t3.display();         cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;         }while(getch()=='c'); }```
Code:

```/*4.  Create an employee class, basing it on Exercise 4 of Chapter 4. The member data should   comprise an int for storing the employee number, and a float for storing the employees   compensation. Member functions should allow the user to enter this data and display it. Write a main   () that allows the user to enter data for three employees and display it.*/ #include<iostream> #include<iomanip> #include<conio.h> using namespace std; class employee{         int emp_num;         float emp_comp; public:         void assign(int en, float ec){ emp_num=en; emp_comp=ec;}         void disp() const { cout<<endl<<setw(25)<<emp_num<<setw(25)<<emp_comp;} }; void main(void) {         cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";         cout<<"-------------------------------------------------------------------------------\n"<<endl;                 employee x; int a; float b;                 do{         for(int i=0; i<3;){         cout<<"Enter the employee "<<++i<<" number      : "; cin>>a;         cout<<"Enter the employee "<<  i<<" compensation: "; cin>>b;         x[i-1].assign(a, b);}         cout<<setw(25)<<"employees number"<<setw(25)<<"employee's compensation";         for(int j=0; j<3; j++) { x[j].disp();}         cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;         }while(getch()=='c'); }```
Code:

```/*5.  Start with the date structure in Exercise 5 in Chapter 4 and transform it into a date class. Its   member data should consist of three ints: month, day, and year. It should also have two member   functions: getdate(), which allows the user to enter a date in 12/31/97 format, and showdate(), which   displays the date. */ #include<iostream> #include<conio.h> using namespace std; class date{         int day, month, year;         char c; public:         void getdate(){         cout<<"Enter date in [12/31/97] format: ";         cin >>day>>c>>month>>c>>year;}         void showdate() const { cout<<"Date is: "<<day<<c<<month<<c<<year;}}; void main(void) {         cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";         cout<<"-------------------------------------------------------------------------------\n"<<endl;                 date x;                 do{                 x.getdate(); x.showdate();         cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;         }while(getch()=='c'); }```
• 12-27-2006, 03:08 PM
Amahdy
Code:

```/*6.  Extend the employee class of Exercise 4 to include a date class (see Exercise 5) and an etype enum   (see Exercise 6 in Chapter 4). An object of the date class should be used to hold the date of first   employment; that is, the date when the employee was hired. The etype variable should hold the   employees type: laborer, secretary, manager, and so on. These two items will be private member   data in the employee declaration, just like the employee number and salary. Youll need to extend the   getemploy() and putemploy() functions to obtain this new information from the user and display it.   These functions will probably need switch statements to handle the etype variable. Write a main()   program that allows the user to enter data for three employee variables, which then displays this data. */ #include<iostream> #include<iomanip> #include<conio.h> using namespace std; class employee{         class date{                 int day, month, year;                 char c;         public:                 void getdate(){                 cout<<"Enter date in [12/31/97] format: ";                 cin >>day>>c>>month>>c>>year;}                 void showdate() const { cout<<setw(10)<<day<<c<<month<<c<<year;}};         int emp_num; float emp_comp;         date y; char *ret;         enum etype { laborer, secretary, manager, accountant, executive, researcher }; public:         void putemploy(int en, float ec);         void getemploy() const {                 cout<<setw(15)<<emp_num<<setw(25)<<emp_comp<<setw(15)<<ret;                 y.showdate(); cout<<endl; }}; void employee::putemploy(int en, float ec){         emp_num=en; emp_comp=ec;         etype x; y.getdate();         cout<<"Enter employee type (first letter only)"<<endl             <<"(laborer, secretary, manager, accountant, executive, researcher): ";         switch(getche()){         case 'l': x=laborer  ; break;         case 's': x=secretary ; break;         case 'm': x=manager  ; break;         case 'a': x=accountant; break;         case 'e': x=executive ; break;         case 'r': x=researcher;}         switch(x){         case 0: ret = "laborer"  ; break;         case 1: ret = "secretary" ; break;         case 2: ret = "manager"  ; break;         case 3: ret = "accountant"; break;         case 4: ret = "executive" ; break;         case 5: ret = "researcher"; break;         default: ret = "Undefined";}} void main(void) {         cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";         cout<<"-------------------------------------------------------------------------------\n"<<endl;                 employee x; int a; float b;                 do{         for(int i=0; i<3;){         cout<<"\nEnter the employee "<<++i<<" number      : "; cin>>a;         cout<<"Enter the employee "<<  i<<" compensation: "; cin>>b;         x[i-1].putemploy(a, b);}         cout<<endl<<setw(15)<<"employees number"                           <<setw(25)<<"employee's compensation"                           <<setw(15)<<"Employee type"                           <<setw(15)<<"Date\n";         for(int j=0; j<3; j++) { x[j].getemploy();}         cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;         }while(getch()=='c'); }```
Code:

```/*7.  In ocean navigation, locations are measured in degrees and minutes of latitude and longitude.   Thus if youre lying off the mouth of Papeete Harbor in Tahiti, your location is 149 degrees 34.8   minutes west longitude, and 17 degrees 31.5 minutes south latitude. This is written as 149°34.8W,   17°31.5S. There are 60 minutes in a degree. (An older system also divided a minute into 60   seconds, but the modern approach is to use decimal minutes instead.) Longitude is measured from 0   to 180 degrees, east or west from Greenwich, England, to the international dateline in the Pacific.   Latitude is measured from 0 to 90 degrees, north or south from the equator to the poles.   Create a class angle that includes three member variables: an int for degrees, a float for minutes,   and a char for the direction letter (N, S, E, or W). This class can hold either a latitude variable or a   longitude variable. Write one member function to obtain an angle value (in degrees and minutes) and   a direction from the user, and a second to display the angle value in 179°59.9E format. Also write   a threeargument constructor. Write a main() program that displays an angle initialized with the   constructor, and then, within a loop, allows the user to input any angle value, and then displays the   value. You can use the hex character constant \xF8 which usually prints a degree (°) symbol. */ #include<iostream> #include<conio.h> using namespace std; class angle{         int degrees;         float minutes;         char direction; public:         angle(int deg, float min, char dir){ degrees=deg, minutes=min, direction=dir;}         void getAngle(int deg, float min, char dir){ degrees=deg; minutes=min; direction=dir;}         void disp() const { cout<<degrees<<"\xF8"<<minutes<<"\'"<<direction<<endl;}         }; void main(void) {         cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";         cout<<"-------------------------------------------------------------------------------\n"<<endl;                 angle A(17, 31.5f, 'S');         int a; float b; char c;         A.disp();         do{         cout<<"Enter degrees  : "; cin>>a;         cout<<"Enter minutes  : "; cin>>b;         cout<<"Enter direction: "; cin>>c;         A.getAngle(a, b, c);         A.disp();         cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;         }while(getch()=='c'); }```
Code:

```/*8.  Create a class that includes a data member that holds a serial number for each object created   from the class. That is, the first object created will be numbered 1, the second 2, and so on.   To do this, youll need another data member that records a count of how many objects have been   created so far. (This member should apply to the class as a whole; not to individual objects. What   keyword specifies this?) Then, as each object is created, its constructor can examine this count   member variable to determine the appropriate serial number for the new object.   Add a member function that permits an object to report its own serial number. Then write a main()   program that creates three objects and queries each one about its serial number. They should   respond I am object number 2, and so on.*/ #include<iostream> #include<conio.h> using namespace std; class SN{         static int count;         int serial; public:         SN() { serial=++count;} //could make another function but no need for it !         void disp() const { cout<<"I\'am object number "<<serial<<endl;} };  int SN::count=0; void main(void) {         cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";         cout<<"-------------------------------------------------------------------------------\n"<<endl;                 do{                 SN s;                 for(int i=0; i<3; i++) s[i].disp();         cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;         }while(getch()=='c'); }```
Code:

```/*9.  Transform the fraction structure from Exercise 8, Chapter 4 into a fraction class. Member data is   the fractions numerator and denominator. Member functions should accept input from the user in   the form 3/5, and output the fractions value in the same format. Another member function should   add two fraction values. Write a main() program that allows the user to repeatedly input two   fractions, and which then displays their sum. After each operation ask if the user wants to continue.*/ #include<iostream> #include<conio.h> using namespace std; class fraction{         int numerator, denominator;         char c;         void dispFct() const { cout<<numerator<<"/"<<denominator;} public:         void getFct(){ cout<<"Enter fraction: "; cin>>numerator>>c>>denominator;}         void addFct(fraction x, fraction y){                 numerator=x.numerator*y.denominator+x.denominator*y.numerator;                 denominator=x.denominator*y.denominator;                 cout<<"Sum = "; dispFct();}}; void main(void) {         cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";         cout<<"-------------------------------------------------------------------------------\n"<<endl;                 fraction f;         do{                 f.getFct(); f.getFct();                 f.addFct(f, f);         cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;         }while(getch()=='c'); }```
Code:

```/*10.  Create a class called ship that incorporates a ships number and location. Use the approach of   Exercise 8 to number each ship object as it is created. Use two variables of the angle class from   Exercise 7 to represent the ships latitude and longitude. A member function of the ship class should   get a position from the user and store it in the object; another should report the serial number and   position. Write a main() program that creates three ships, asks the user to input the position of each,   and then displays each ships number and position. */ #include<iostream> #include<conio.h> using namespace std; class SN{         static int count;         int serial; public:         SN() { serial=++count;}         void disp() const { cout<<serial;} };  int SN::count=0; class angle{         int degrees;         float minutes;         char direction; public:         void getAngle(){                 cout<<"Enter degrees  : "; cin>>degrees;                 cout<<"Enter minutes  : "; cin>>minutes;                 cout<<"Enter direction: "; cin>>direction;}         void disp() const { cout<<degrees<<"\xF8"<<minutes<<"\'"<<direction;}}; class ship{         SN s;         angle a1, a2; public:         void getPos() { a1.getAngle(); a2.getAngle();}         void disp() const {                 cout<<"Ship number: "; s.disp();                 cout<<" position: "; a1.disp(); cout<<", "; a2.disp(); cout<<endl;}}; void main(void) {         cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";         cout<<"-------------------------------------------------------------------------------\n"<<endl;                 ship s;         do{                 for(int i=0; i<3; i++) s[i].getPos();                 for(int j=0; j<3; j++) s[j].disp();         cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;         }while(getch()=='c'); }```
• 12-27-2006, 03:09 PM
Amahdy
Code:

```/*11.  Modify the fourfunction fraction calculator of Exercise 12, Chapter 5 to use a fraction class   rather than a structure. There should be member functions for input and output, as well as for the   four arithmetical operations. While youre at it, you might as well install the capability to reduce   fractions to lowest terms. Heres a member function that will reduce the fraction object of which it is   a member to lowest terms. It finds the greatest common divisor (gcd) of the fractions numerator   and denominator, and uses this gcd to divide both numbers.   void fraction::lowterms()    // change ourself to lowest terms     {     long tnum, tden, temp, gcd;     tnum = labs(num);          // use nonnegative copies     tden = labs(den);          //    (needs cmath)     if(tden==0 )  // check for n/0         { cout << Illegal fraction: division by 0; exit(1); }     else if( tnum==0 )        // check for 0/n         { num=0; den = 1; return; }     // this while loop finds the gcd of tnum and tden     while(tnum != 0)         {         if(tnum < tden)        // ensure numerator larger         { temp=tnum; tnum=tden; tden=temp; }  // swap them         tnum = tnum  tden;    // subtract them         }     gcd = tden;                // this is greatest common divisor     num = num / gcd;          // divide both num and den by gcd     den = den / gcd;          // to reduce frac to lowest terms     }     You can call this function at the end of each arithmetic function, or just before you perform output.   Youll also need the usual member functions: four arithmetic operations, input, and display. You may   find a twoargument constructor useful. */ #include<iostream> #include<conio.h> using namespace std; class fraction{ public:         int numerator, denominator;         void fadd(fraction a, fraction b);         void fsub(fraction a, fraction b);         void fmul(fraction a, fraction b);         void fdiv(fraction a, fraction b);         void lowterms();         void disp() const { cout<<"Answer = "<<numerator<<"/"<<denominator;}}; void fraction::lowterms(){ /*===Edited By Amahdy=====*/         long tnum, tden, temp;         tnum = labs(numerator); //labs() to get the absolute value of a long.         tden = labs(denominator);         if(!(tnum)){ numerator=0; denominator=1; return;}         while(tnum != 0){         if(tnum<tden){ temp=tnum; tnum=tden; tden=temp;}         tnum-=tden;}         numerator/=tden; denominator/=tden;} void fraction::fadd(fraction a, fraction b){         numerator  =a.numerator*b.denominator+a.denominator*b.numerator;         denominator=a.denominator*b.denominator;} void fraction::fsub(fraction a, fraction b){         numerator  =a.numerator*b.denominator-a.denominator*b.numerator;         denominator=a.denominator*b.denominator;} void fraction::fmul(fraction a, fraction b){         numerator  =a.numerator*b.numerator;         denominator=a.denominator*b.denominator;} void fraction::fdiv(fraction a, fraction b){         if(b.numerator != 0){         numerator  =a.numerator*b.denominator;         denominator=b.numerator*a.denominator;}         else        cout<<"Math error !"<<endl;} void main(void) {         cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";         cout<<"-------------------------------------------------------------------------------\n"<<endl;                 fraction f; char c, op;         do{                 cout<<"Enter your task : ";                 cin >>f.numerator>>c>>f.denominator>>op>>f.numerator>>c>>f.denominator;                 if(!f.denominator || !f.denominator) {cout<<"Illeagle fraction !"<<endl; op=false;}                 switch(op) {                 case '+':        f.fadd(f, f); break;                 case '-':        f.fsub(f, f); break;                 case '*':        f.fmul(f, f); break;                 case '/':        f.fdiv(f, f); break;                 default:        cout<<"Unknow operator please try again !"<<endl;}                 f.lowterms();                 cout<<"Answer = "<<f.numerator<<c<<f.denominator;         cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;         }while(getch()=='c'); }```
Code:

```/*12.  Note that one advantage of the OOP approach is that an entire class can be used, without   modification, in a different program. Use the fraction class from Exercise 11 in a program that   generates a multiplication table for fractions. Let the user input a denominator, and then generate all   combinations of two such fractions that are between 0 and 1, and multiply them together. Heres an   example of the output if the denominator is 6:         1/6    1/3    1/2    2/3    5/6      1/6    1/36    1/18  1/12  1/9    5/36   1/3    1/18    1/9    1/6    2/9    5/18   1/2    1/12    1/6    1/4    1/3    5/12   2/3    1/9    2/9    1/3    4/9    5/9   5/6    5/36    5/18  5/12  5/9    25/36 */ #include<iostream> #include<iomanip> #include<conio.h> using namespace std; class fraction{         int numerator, denominator; public:         fraction(int num, int den): numerator(num), denominator(den) {}         void fmul(fraction a, fraction b);         void lowterms();         void assign(int num, int den){ numerator=num; denominator=den;}         void dispN() const { cout<<numerator<<"/"<<denominator;}         void disp() const { cout<<setw(7)<<numerator<<"/"<<setw(3)<<denominator;}}; void fraction::lowterms(){ /*===Edited By Amahdy=====*/         long tnum, tden, temp;         tnum = labs(numerator);         tden = labs(denominator);         if(!(tnum)){ numerator=0; denominator=1; return;}         while(tnum != 0){         if(tnum<tden){ temp=tnum; tnum=tden; tden=temp;}         tnum-=tden;}         numerator/=tden; denominator/=tden;} void fraction::fmul(fraction a, fraction b){         numerator  =a.numerator*b.numerator;         denominator=a.denominator*b.denominator;} void main(void) {         cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";         cout<<"-------------------------------------------------------------------------------\n"<<endl;                 fraction f(0, 0), f1(0, 0), f2(0, 0); int x;         do{                 cout<<"Enter a number : "; cin>>x; cout<<"  ";                 for(int i=0; i<x-1;){ f.assign(++i, x); f.lowterms(); f.disp();}                 cout<<endl<<setfill('-')<<setw(10*x)<<' '<<setfill(' ');                 for(int j=0; j<x-1;){                         cout<<endl; f.assign(++j, x); f.lowterms(); f.dispN();                         for(int k=0; k<x-1;){                                 f1.assign(++k, x); f2.assign(j, x);                                 f.fmul(f1, f2); f.lowterms(); f.disp();}}         cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;         }while(getch()=='c'); }```
• 12-27-2006, 03:10 PM
Amahdy
CHAPTER 7ARRAYS AND STRINGS

Quote:

Questions:
----------
1. An array element is accessed using
a. a first-in-first-out approach.
b. the dot operator.
c. a member name.
d. an index number.
2. All the elements in an array must be the _________ data type.
3. Write a statement that defines a one-dimensional array called doubleArray of type double that holds 100 elements.
4. The elements of a 10-element array are numbered from ________ to ________.
5. Write a statement that takes element j of array doubleArray and writes it to cout with the insertion operator.
6. Element doubleArray is which element of the array?
a. The sixth
b. The seventh
c. The eighth
d. Impossible to tell
7. Write a statement that defines an array coins of type int and initializes it to the values of the penny, nickel, dime, quarter, half-dollar, and dollar.
8. When a multidimensional array is accessed, each array index is
a. separated by commas.
b. surrounded by brackets and separated by commas.
c. separated by commas and surrounded by brackets.
d. surrounded by brackets.
9. Write an expression that accesses element 4 in subarray 2 in a two-dimensional array called twoD.
10. True or false: In C++ there can be an array of four dimensions.
11. For a two-dimensional array of type float, called flarr, write a statement that declares the array and initializes the first subarray to 52, 27, 83; the second to 94, 73, 49; and the third to 3, 6, 1.
12. An array name, used in the source file, represents the ________ of the array.
13. When an array name is passed to a function, the function
a. accesses exactly the same array as the calling program.
b. accesses a copy of the array passed by the program.
c. refers to the array using the same name as that used by the calling program.
d. refers to the array using a different name than that used by the calling program.
14. Tell what this statement defines: employee emplist;
15. Write an expression that accesses a structure member called salary in a structure variable that is the 17th element in an array called emplist.
16. In a stack, the data item placed on the stack first is
a. not given an index number.
b. given the index number 0.
c. the first data item to be removed.
d. the last data item to be removed.
17. Write a statement that defines an array called manybirds that holds 50 objects of type bird.
18. True or false: The compiler will complain if you try to access array element 14 in a 10-element array.
19. Write a statement that executes the member function cheep() in an object of class bird that is the 27th element in the array manybirds.
20. A string in C++ is an _________ of type _________.
21. Write a statement that defines a string variable called city that can hold a string of up to 20 characters (this is slightly tricky).
22. Write a statement that defines a string constant, called dextrose, that has the value C6H12O6-H2O.
23. True or false: The extraction operator (>>) stops reading a string when it encounters a space.
24. You can read input that consists of multiple lines of text using
a. the normal cout << combination.
b. the cin.get() function with one argument.
c. the cin.get() function with two arguments.
d. the cin.get() function with three arguments.
25. Write a statement that uses a string library function to copy the string name to the string blank.
26. Write the declaration for a class called dog that contains two data members: a string called breed and an int called age. (Dont include any member functions.)
27. True or false: You should prefer C-strings to the Standard C++ string class in new programs.
28. Objects of the string class
a. are zero-terminated.
b. can be copied with the assignment operator.
c. do not require memory management.
d. have no member functions.
29. Write a statement that finds where the string cat occurs in the string s1.
30. Write a statement that inserts the string cat into string s1 at position 12.
__________
Quote:

My answers:
-----------
1. an index number.
2. same.
3. double doubleArray;
4. 0, 9.
5. cout<<doubleArray[j-1];
6. The eighth.
7. int coins = {penny, nickel, dime, quarter, half-dollar, dollar};
8. surrounded by brackets.
9. twoD;
10. True;
11. float flarr = {52,27,83, 94,73,49, 3,6,1};
12. name.
13. accesses exactly the same array as the calling program.
14. An array called emplist of type employee with size 1000.
15. emplist.salary;
16. the last data item to be removed.
17. bird manybirds;
18. False.
19. manybirds.cheep();
20. array, char.
21. char city;
22. const char[] = C6H12O6-H2O;
23. True.
24. the cin.get() function with three arguments.
25. strcpy(name, blank);
26. class dog{ string breed; int age;};
27. False.
28. can be copied with the assignment operator, do not require memory management.
29. s1.find("cat");
30. s1.insert(12, "cat");
___________
Quote:

Answers:
--------
1. d
2. same
3. double doubleArray;
4. 0, 9
5. cout << doubleArray[j];
6. c
7. int coins[] = { 1, 5, 10, 25, 50, 100 };
8. d
9. twoD
10. True
11. float flarr = { {52,27,83}, {94,73,49}, {3,6,1} };
12. memory address
13. a, d
14. an array with 1000 elements of structure or class employee
15. emplist.salary
16. d
17. bird manybirds;
18. False
19. manybirds.cheep();
20. array, char
21. char city (An extra byte is needed for the null character.)
22. char dextrose[] = C6H12O6-H2O;
23. True
24. d
25. strcpy(blank, name);
26.
class dog
{
private:
char breed;
int age;
};

27. False
28. b, c
29. int n = s1.find(cat);
30. s1.insert(12, cat);
________
• 12-27-2006, 03:13 PM
Amahdy
CHAPTER 7ARRAYS AND STRINGS code;

Code:

```/**1.  Write a function called reversit() that reverses a C-string (an array of char). Use a for loop that   swaps the first and last characters, then the second and next-to-last characters, and so on. The   string should be passed to reversit() as an argument.   Write a program to exercise reversit(). The program should get a string from the user, call reversit(),   and print out the result. Use an input method that allows embedded blanks. Test the program with   Napoleons famous phrase, Able was I ere I saw Elba.*/ #include<iostream> #include<string> #include<conio.h> using namespace std; void reversit(char str[]){         char tmp; int k=strlen(str);         for(int i=0; i<(k/2); i++){         tmp=str[i]; str[i]=str[k-i-1]; str[k-i-1]=tmp;}} void main(void) {         cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";         cout<<"-------------------------------------------------------------------------------\n"<<endl;                 char mystr;                 do{         cout<<"Enter a string: "; cin>>mystr;         reversit(mystr); cout<<mystr;         cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;         }while(getch()=='c'); }```
Code:

```/**2.  Create a class called employee that contains a name (an object of class string) and an employee   number (type long). Include a member function called getdata() to get data from the user for insertion   into the object, and another function called putdata() to display the data. Assume the name has no   embedded blanks.   Write a main() program to exercise this class. It should create an array of type employee, and then   invite the user to input data for up to 100 employees. Finally, it should print out the data for all the   employees.*/ #include<iostream> #include<string> #include<iomanip> #include<conio.h> using namespace std; class employee{         string name;         long emp_num; public:         void putdata(){         cout<<"\nEnter the employee name: "; cin>>name;         cout<<"Enter the employee number: "; cin>>emp_num;}         void getdata(){ cout<<endl<<setw(10)<<name<<setw(25)<<emp_num;}}; void main(void) {         cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";         cout<<"-------------------------------------------------------------------------------\n"<<endl;                 employee emp; int i=0;                 do{                 while(true){                 emp[i++].putdata();                 if(i<100){                         cout<<"Enter more ? (y) to continue : ";                         if(toupper(getche())=='Y') continue;}                 break;}                 cout<<"\nEmployee name"<<setw(25)<<"Employee number";                 for(int j=0; j<i; j++) emp[j].getdata();         cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;         }while(getch()=='c'); }```
Code:

```/**3.  Write a program that calculates the average of up to 100 English distances input by the user.   Create an array of objects of the Distance class, as in the ENGLARAY example in this chapter. To   calculate the average, you can borrow the add_dist() member function from the ENGLCON example in   Chapter 6. Youll also need a member function that divides a Distance value by an integer. Heres   one possibility:   void Distance::div_dist(Distance d2, int divisor)     {     float fltfeet = d2.feet + d2.inches/12.0;     fltfeet /= divisor;     feet = int(fltfeet);     inches = (fltfeet-feet) * 12.0;     } */ #include<iostream> #include<string> #include<iomanip> #include<conio.h> using namespace std; class Distance{       int feet; float inches;   public:           Distance(): feet(0), inches(0) {}       void getdist(){       cout<<"\nEnter feet: "; cin>>feet;       cout<<"Enter inches: "; cin>>inches;}           void add_dist(Distance d2, Distance d3);           void div_dist(Distance d2, int divisor);       void showdist() const { cout<<feet<<"\'-"<<inches<<'\"';}}; void Distance::add_dist(Distance d2, Distance d3) {   inches=d2.inches+d3.inches; feet=0;   if(inches>=12.0){ inches -= 12.0; feet++;}   feet += d2.feet+d3.feet; } void Distance::div_dist(Distance d2, int divisor) {   float fltfeet=d2.feet+d2.inches/12.0;   fltfeet /= divisor; feet=int(fltfeet);   inches=(fltfeet-feet)*12.0; } void main(void) {         cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";         cout<<"-------------------------------------------------------------------------------\n"<<endl;                 Distance dist, tmp; int i=0;                 do{         while(true){         dist[i].getdist(); tmp.add_dist(tmp, dist[i++]);         if(i<100){                 cout<<"Enter more ? (y) to continue : ";                 if(toupper(getche())=='Y') continue;}         break;}         tmp.div_dist(tmp, i); cout<<"\nAverage is: "; tmp.showdist();         cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;         }while(getch()=='c'); }```
Code:

```/*4.  Start with a program that allows the user to input a number of integers, and then stores them in   an int array. Write a function called maxint() that goes through the array, element by element, looking   for the largest one. The function should take as arguments the address of the array and the number   of elements in it, and return the index number of the largest element. The program should call this   function and then display the largest element and its index number. (See the SALES program in this   chapter.) */ #include<iostream> #include<conio.h> using namespace std; int maxint(int arr[], int bound){         int max=0;         for(int j=1; j<bound; j++) max= arr[max]>arr[j]? max:j;         return max;} void main(void) {         cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";         cout<<"-------------------------------------------------------------------------------\n"<<endl;                 do{                 int a, i=1;         cout<<"Enter numbers : ( to quit) "; cin>>a;         while(a[i-1] || i==100) cin>>a[i++];         cout<<"The maximum is: "<<a[maxint(a, i)];         cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;         }while(getch()=='c'); }```
• 12-27-2006, 03:14 PM
Amahdy
Code:

```/*5.  Start with the fraction class from Exercises 11 and 12 in Chapter 6. Write a main() program that   obtains an arbitrary number of fractions from the user, stores them in an array of type fraction,   averages them, and displays the result*/ #include<iostream> #include<conio.h> using namespace std; class fraction{         char c;         int numerator, denominator; public:         void fadd(fraction a, fraction b);         void fdiv(fraction a, fraction b);         void getfrac(){ cout<<"Enter fraction: "; cin>>numerator>>c>>denominator;}         void disp() const { cout<<"Maximum = "<<numerator<<"/"<<denominator;}         float getFl(){ if(denominator) return numerator/denominator; else return 0;}}; void fraction::fadd(fraction a, fraction b){         numerator  =a.numerator*b.denominator+a.denominator*b.numerator;         denominator=a.denominator*b.denominator;} void fraction::fdiv(fraction a, fraction b){         if(b.numerator != 0){         numerator  =a.numerator*b.denominator;         denominator=b.numerator*a.denominator;}         else        cout<<"Math error !"<<endl;}         int maxfrc(fraction arr[], int bound){         int max=0;         for(int j=1; j<bound; j++) max= arr[max].getFl()>arr[j].getFl()? max:j;         return max;} void main(void) {         cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";         cout<<"-------------------------------------------------------------------------------\n"<<endl;                 do{                 fraction a; int i=1;         cout<<"( to quit):\n"; a.getfrac();         while(a[i-1].getFl() || i==100) a[i++].getfrac();         a[maxfrc(a, i)].disp();         cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;         }while(getch()=='c'); }```
Code:

```/*6.  In the game of contract bridge, each of four players is dealt 13 cards, thus exhausting the entire   deck. Modify the CARDARAY program in this chapter so that, after shuffling the deck, it deals four   hands of 13 cards each. Each of the four players hands should then be displayed. */ #include<iostream> #include<conio.h> using namespace std; #include<cstdlib> #include<ctime> enum Suit{ clubs, diamonds, hearts, spades}; const int jack  = 11; const int queen = 12; const int king  = 13; const int ace  = 14; class card{       int number;       Suit suit;   public:       void set(int n, Suit s){ suit=s; number=n;}       void display();}; void card::display() {         if(number>=2 && number<=10) cout<<number;         else switch(number) {           case jack:    cout<<"J";    break;           case queen:    cout<<"Q";    break;           case king:    cout<<"K";    break;           case ace:      cout<<"A";}         switch(suit) {           case clubs:    cout<<char(5); break;           case diamonds: cout<<char(4); break;           case hearts:  cout<<char(3); break;           case spades:  cout<<char(6);}         cout<<"  "; } void main(void) {         cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";         cout<<"-------------------------------------------------------------------------------\n"<<endl;                 card deck; int j, i;         do{                 i=0;         for(j=0; j<52; j++){                 int num=(j%13)+2; Suit su=Suit(j/13);                 deck[j].set(num, su);}         srand(time(NULL));         for(j=0; j<52; j++){                 int k=rand()%52; card temp=deck[j];                 deck[j]=deck[k]; deck[k]=temp;}         cout<<"\nHand "<<++i<<": ";         for(j=0; j<52; j++){ deck[j].display(); if(!((j+1)%13)&&i<4) cout<<"\nHand "<<++i<<": ";;}         cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;         }while(getch()=='c'); }```
Code:

```/*7.  One of the weaknesses of C++ for writing business programs is that it does not contain a built-in   type for monetary values such as \$173,698,001.32. Such a money type should be able to store a   number with a fixed decimal point and about 17 digits of precision, which is enough to handle the   national debt in dollars and cents. Fortunately, the built-in C++ type long double has 19 digits of   precision, so we can use it as the basis of a money class, even though it uses a floating decimal.   However, well need to add the capability to input and output money amounts preceded by a dollar   sign and divided by commas into groups of three digits; this makes it much easier to read large   numbers. As a first step toward developing such a class, write a function called mstold() that takes a   money string, a string representing a money amount like   \$1,234,567,890,123.99   as an argument, and returns the equivalent long double.   Youll need to treat the money string as an array of characters, and go through it character by   character, copying only digits (1 to 9) and the decimal point into another string. Ignore everything   else, including the dollar sign and the commas. You can then use the _atold() library function (note   the initial underscore; header file STDLIB.H or MATH.H) to convert the resulting pure string to a long   double. Assume that money values will never be negative. Write a main() program to test mstold() by   repeatedly obtaining a money string from the user and displaying the corresponding long double.  */ #include<iostream> #include<conio.h> #include<stdlib.h> #include<string> using namespace std; long mstold(char strm[]) {         string s=" 0123456789"; char ret;         //long double x;         for(int i=0, j=0; i<strlen(strm); i++)                 if(s.find(strm[i])<20) ret[j++]=strm[i];                 return atol(ret); } void main(void) {         cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";         cout<<"-------------------------------------------------------------------------------\n"<<endl;                 char mon;         do{         cout<<"Enter a monetary value: "; cin>>mon; cout<<mstold(mon);         cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;         }while(getch()=='c'); }```
Code:

```/*8.  Another weakness of C++ is that it does not automatically check array indexes to see if they are   in bounds. (This makes array operations faster but less safe.) We can use a class to create a safe   array that checks the index of all array accesses.   Write a class called safearay that uses an int array of fixed size (call it LIMIT) as its only data   member. There will be two member functions. The first, putel(), takes an index number and an int   value as arguments and inserts the int value into the array at the index. The second, getel(), takes an   index number as an argument and returns the int value of the element with that index.   safearay sa1;          // define a safearay object   int temp = 12345;      // define an int value   sa1.putel(7, temp);    // insert value of temp into array at index 7   temp = sa1.getel(7);    // obtain value from array at index 7   Both functions should check the index argument to make sure it is not less than 0 or greater than   LIMIT-1. You can use this array without fear of writing over other parts of memory.   Using functions to access array elements doesnt look as eloquent as using the [] operator. In   Chapter 8 well see how to overload this operator to make our safearay class work more like built-   in arrays. */ #include<iostream> #include<conio.h> using namespace std; const int LIMIT=100; class safearay{         int arr[LIMIT]; public:         void putel(int index, int value){ if(index>-1 && index<LIMIT) arr[index]=value;}         int getel(int index){ if(index>-1 && index<LIMIT) return arr[index];}}; void main(void) {         cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";         cout<<"-------------------------------------------------------------------------------\n"<<endl;                 safearay sa1; int temp=12345;         do{     sa1.putel(7, temp);        temp=sa1.getel(7);         cout<<temp;         cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;         }while(getch()=='c'); }```
• 04-27-2010, 04:01 PM
muhammadlodhi
BISMILLAH.

I didnt want to reply as you say but it was necessary after that exercise where can i find the solution i need more of chapter 07 and chapter 10???
• 12-01-2012, 05:12 AM
wasi
needs operator over loading problem solutions
• 02-11-2016, 06:29 AM
reg1965
Your solution to chapter 2 exercise 12 doesn't work. Consider entering £3.55. The correct answer should be £3.11.0. Your solution results in £3.10.11.
My solution below solves this error:

Code:

```#include<iostream> using namespace std; int ch1_ex12(){     int pPounds=0,pShillings=0,pPence=0;     float pPencePart;     char pDummy;     cout << "Enter decimal pounds: ";     cin >> pPounds >> pDummy >> pPence;     // get shillings     pShillings = pPence / 5;     // get pence     pPencePart = static_cast<float>(pPence - (pShillings * 5));     pPence = static_cast<float>((pPencePart  / 5) * 12);     // output     cout << "\nEquivalent in old notation = " << '\x9c' << pPounds << "." << pShillings << "." << pPence << "." << endl;     return 0; }```
Show 40 post(s) from this thread on one page
{"ft_lang_label":"__label__en","ft_lang_prob":0.7309563,"math_prob":0.9030644,"size":5580,"snap":"2021-21-2021-25","text_gpt3_token_len":1533,"char_repetition_ratio":0.14992826,"word_repetition_ratio":0.057651993,"special_character_ratio":0.32867384,"punctuation_ratio":0.22689076,"nsfw_num_words":3,"has_unicode_error":false,"math_prob_llama3":0.9858792,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2021-06-23T05:20:37Z\",\"WARC-Record-ID\":\"<urn:uuid:499cde36-0496-4fc5-9d92-aee19fa26174>\",\"Content-Length\":\"120167\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:52cfd0a5-88f4-449e-95ca-4f5e513a40bf>\",\"WARC-Concurrent-To\":\"<urn:uuid:2ad21507-21d0-45cc-9e74-36d6776fc2d3>\",\"WARC-IP-Address\":\"18.217.169.143\",\"WARC-Target-URI\":\"https://forums.devx.com/printthread.php?s=031c400d0ec39ac5a74cd8cf26555d50&t=158122&pp=15&page=2\",\"WARC-Payload-Digest\":\"sha1:DKILP3A6HAQ7GJ64LZXJTRJUBZZQCBQV\",\"WARC-Block-Digest\":\"sha1:F3BXRWZ2JPMKPRGQDUTICNHDW5PHEU4E\",\"WARC-Identified-Payload-Type\":\"application/xhtml+xml\",\"warc_filename\":\"/cc_download/warc_2021/CC-MAIN-2021-25/CC-MAIN-2021-25_segments_1623488534413.81_warc_CC-MAIN-20210623042426-20210623072426-00038.warc.gz\"}"}