Description

C++ Complete Solutions - E BALAGURUSAMYChapter 1: 1.1: What do you think are the major issues facing the software industry today? Ans:Many software products are either not finished or not used or not delivered for some major errors. Today some of the quality issues that must be considered for software industry are: 1. Correctness. 2. Maintainability. 3. Reusability. 4. Openness and interoperability. 5. Portability. 6. Security. 7. Integrity. 8. User friendliness. 1.2:Briefly discuss the software evolution during the period 1950— 1990. Ans:In 1950, the first three modern programming languages whose descendants are still in widespread today. 1. FORTRAN (1955), the “FORmula TRANslator” 2. LISP (1958) the “LISt Procssor”. 3. COBOL, the COmmon Business Oriented Language. Some important language that were developed in 1950 to 1960 are: 1. 1951 Regional Assembly Language 2. 19952 Autocode 3. 1954 IPL 4. 1955 FLOW-MATIC 5. 1957COMTRAN 6. 1959COBOL 7. 1962APL 1.3: What is procedure-oriented programming? What are its main characteristics? Ans:Conventional programming, using high level language such as COBOL, FORTAN and C is commonly known as procedure oriented programming. Characteristics : a) Emphasis is on doing things (algorithms) b) Large programs are divided into small programs known as function. c) Most of the function share global data. d) Data move openly around the system from function to function. e) Function transform data from one form to another. 1.4: Discuss an approach to the development of procedure-oriented programs. Ans: In the procedure-oriented approach, the problem is viewed as a sequence of things to be done such as 1. reading 2. Calculating 3. Printing. A number of functions are written to accomplish these tasks. 1.5: Describe how data are shared by functions in a procedure-oriented program. Ans: In a multi-function program, many important data items are placed as global so that they may be accessed by all the functions. Each function may have its own local data. 1.6: What is object-oriented programming? How is it different from the procedureoriented programming? Ans: Object oriented programming (OOP)is an approach that provides a way of modularizing programs by creating partitioned memory area for both data and functions that can be used as templates for creation copies of such modules on demand. Different between OOP(Object oriented programming) & POP(Procedure oriented programming): 1. OOP has data hading feature for which the data of a class cannot be accessed by the member function of other class but POP has no such feature. 2. In OOP we can design our own data-type which is same as built in data type. But in POP we can not do this. 1.7: How are data and functions organized in an object-oriented program? Ans: Data and functions are belongs to a class. Data is called data member and functions are called member functions. There is a visibility-mode such as public and private. Generally data is private and functions are public. 1.8: What are the unique advantages of an object-oriented programming paradigm? Ans: The unique advantage of object-oriented program paradigm is to have a working definition of OOP before we proceed further. 1.9: Distinguish between the following terms: (a) Objects and classes (b) Data abstraction and data encapsulation (c) Inheritance and polymorphism (d) Dynamic binding and message passing Ans: (a) Objects are the basic run-time entities which contain data and code to manipulate data where the entire set of data and code of an object can be made as a user-defined data type with the help of a class. In short, objects are numbers of classes. (b) Describing the functionality of a class independent of its implementation is called data abstraction. Where data encapsulation means the wrapping up of data and functions into a single unit. (c) The mechanism of deriving a new class from an old one is called inheritance, where polymorphism means one thing with several distinct terms. (d) Binding refers to the linking of a procedure call to be executed in response to the call. When binding occurs at run-time, then it is known as dynamic-binding. Massage passing involves specifying the name of the object, the name of the function and the information to be sent 1.10: What kinds of things can become objects in 00P? Ans:Objects are the basic run-time entities in an object-oriented system. They may represent a person, a place, a bank account, a table of data or any item that the program has to handle. 1.11: Describe inheritance as applied to OOP. Ans:Inheritance is one of the most powerful feature of object-oriented programming. Inheritance is the process of creating new class from existing class. The new class is called derived class and existing class is called base class. 1.12:What do you mean by dynamic binding? How is it useful in OOP? Ans:Binding refers to the linking of a procedure call to be executed in response to the call. When binding occurs at run time it is known as dynamic binding. Dynamic binding is useful in OOP such as a function call associated with a polymorphic reference depends on the dynamic type of that reference. 1. (i) Object-oriented systems can scale up better from small to large. 1. (e) One problem with 00P is that once a class is created it can never be changed. 2.13:Now does object-oriented approach differ from object-based approach? Ans:Object-based programming do not support inheritance and dynamic binding but object-oriented programming do so. (h) Object oriented programs are executed much faster than conventional programs. 3. Hypertext. Object oriented database.15:State whether the following statements are TRUE or FALSE. Ans:Areas of application of OOP technology are : 1. (f) Inheritance means the ability to reuse the data values of one object by (g) Polymorphism is extensively used in implementing inheritance. hypermedia . Decision support and office automation system.14:List a few areas of application of 001″ technology. 4.1. (c) One of the striking features of object-oriented programming is the division of programs into objects that represent real-world entities. 5. Real-time system. (b) The main emphasis of procedure-oriented programming is on algorithms rather than on data. (d) Wrapping up of data of different types into a single unit is known as encapsulation. (a) In procedure-oriented programming. (j) Object-oriented approach cannot be used to create databases. Simulation and modeling. all data are shared by all functions. Ans: a> FALSE b> TRUE c> TRUE d> FALSE e> FALSE f> TRUE g> TRUE h> FALSE . i> TRUE j> FALSE . 2.1: State whether the following statements are TRUE or FALSE.4: What do you think is the main advantage of the comment / / in C++ as compared to the old C type comment? Ans: ‘//’ is more easy and time-saving than ‘/* */’ 2. it is very easy to add new features to the existing structure of an object. (b) In C++. 10 The output function printfl) cannot be used in C++ programs. we can easily recognize whether a program is written in C or C++. all C peograms will run under C++ compilers. a function contained within a class is called a member function. (c) Looking at one or two lines of code. (d) In C++.Chapter 2: 2. Ans: a> FALSE b> TRUE c> FALSE *** most lines of codes are the same in C & C++ d> TRUE e> TRUE f> FALSE 2. Include files 2. (a) Since C is a subset of C++. (e) The concept of using one operator for different purposes is known as aerator overloading.5:Describe the major parts of a C++ program. Class declaration . Ans: Major parts of a C++ program : 1. 2.2: Why do we need the preprocessor directive #include<iostream>? Ans:‘#include<iostream>’ directive causes the preprocessor to add-the contents of iostream file to the program.3: How does a main() function in C++ differ from main{} in C? Ans: In C main () by default returns the void type but in C++ it returns integer by default. h> void main() 3 { 4 int i = 0.  Syntax error 2. 7 cout<<modResult<<" ". j=3000. Member function definitions 4.1: Identify the error in the following program. 2. 6 /*comment \*//i = i + 1.h> 2 void main() 3 { 4 int i=10.  floating point Error or divide by zero . 10 } 11 Ans:divResult = i/modResult.3:What will happen when you run the following program? 1 #include<iostream.2:Identify the error in the following program. 1 #include<iostream. 5 cout « i « " ". 6 modResult = i%j.h> 2 void main() 3 { short i=2500. 1 2 #include<iostream.3. i = i + 1. 5 int modResult=0. 9 cout<<divResult. Main function program 2. 5 } 6 Ans:cout >> “i+j=”>> -(i + j). 8 } 9 Ans: /* comment\*//i=i+1. int divResult=0. 4 cour>> "i+j=">> -(i+j).  Illegal structure operation. 7 cout << i. j=5. 8 divResult = i/modResult. Name”<<name. the program will successfully compile but it will show Run Error. Ans: Error a Statement missing cout<<“x=”<<x. if any. >>y.4: Find errors.1: Write a program to display the following output using a single cout statement Maths = 90 Physics = 77 Chemistry = 69 Solution: #include<iostream. (a) cout. b No error c Expressionsyntax-error d Correction cin>>x>>y.Note: If this kind of Error exist in a program. 2. cin >> x: (f) /*Addition*/ z = x + y.h> 1 #include<iomanip. // = m + n: (c) cin >>x. // n = 10.<<“x=” x. (d) cout <<\h ‘Name:” <<name. Illigal character cout<<“\n ‘\’. Statement missing e f No error No error 2. in the following C++ statements. (e) cout <<“Enter value:”. (b) m = 5.h> 2 int main() 3 { 4 . } return 0.h> 3 4 int main() 5 { 6 float a.3:Write a program to input an integer from the keyboard and display on the screen “WELL DONE” that many times. cin>>a>>b."Physics". int mark[]={90. 13 } 14 O U T P U T Enter two values : 10 20 larger value = 20 2.i<3."Chemestry"}. Solution: 1 #include<iostream. } O U T P U T Maths = 90 Physics = 77 Chemistry = 69 2. 7 cout<<" Enter two values :"<<endl.77. for(int i=0.h> 2 #include<iomanip. 12 return 0.69}.i++) { cout<<setw(10)<<sub[i]<<setw(3)<<"="<<setw(4)<<mark[i]<<endl.5 6 7 8 9 10 11 12 13 char *sub[]={"Maths". 10 else 11 cout<<" larger value = "<<b<<endl. 8 if(a>b) 9 cout<<" larger value = "<<a<<endl.2: Write a program to read two numbers from the keyboard and display the larger value on the screen.b. Solution: . i<n. 9 } 10 else 11 { .h> int main() { int n. &c :"<<endl.b.c. c = 25 (b) a = 300. 8 cout<<" x=a/(b-c) = "<<x<<endl. 6 if((b-c)!=0) 7 { x=a/(b-c). cout<<" Enter an integer value ".h> #include<iomanip. Test the program for the following values: (a) a = 250. cin>>n.x.b. c = 70 Solution: #include<iostream. b = 85. 4 cout<<" Enter the value of a. str="WELL DONE". b = 70. char *str. where x = a / b –c.4: Write a program to read the values a. 5 cin>>a>>b>>c. for(int i=0. } return 0.h> 2 int main() 3 { float a.i++) { cout<<str<<endl. b and c and display x. } O U T P U T Enter an integer value 5 W ELL DONE W ELL DONE W ELL DONE W ELL DONE W ELL DONE 2.1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Solution: #include<iostream.h> 1 #include<iomanip. 10 return 0.166667 During Second Run: O U T P U T Enter the value of a.h> 2 #include<iomanip.theta.6:Redo Exercise 2.h> 3 4 int main() 5 { 6 float f. &c : 300 70 70 x= infinity 2.b. } During First Run: O U T P U T Enter the value of a. 11 } 12 : ". .b. 9 cout<<" Temperature in Celsius = "<<theta<<endl. O U T P U T Enter the temperature in Feranhite scale : 105 Temperature in Celsius = 40. x= infinity "<<endl.5 using a class called temp and member functions. 8 theta=((f-32)/9)*5.5: Write a C++ program that will ask for a temperature in Fahrenheit and display it in Celsius Solution: 1 #include<iostream.555557 2. &c : 250 85 25 x=a/(b-c) = 4.12 13 14 15 16 17 18 cout<<" } return 0. cout<<" Enter the temperature in Feranhite scale 7 cin>>f. 10 11 float temp::conversion(float f) 12 { 13 theta=((f-32)/9)*5. 9 }.h> 3 #include<iomanip. 21 return 0.conversion(f)<<endl. 18 cout<<" Enter temperature in Farenheite scale :"<<endl. 14 } 15 int main() 16 { 17 temp t. float f.Solution: 1 2 #include<iostream. 20 cout<<" Temperature in Celsius scale = "<<t. 22 } 23 24 O U T P U T Enter the temperature in Feranhite scale : 112 Temperature in Celsius = 44.444443 .theta. return theta. public: 8 float conversion(float f).h> 4 5 class temp 6 { 7 float f. 19 cin>>f. a variable can be declared any where in the program but before the using of the variable. 3.1:Enumerate the rules of naming variables in C++. In C++. How do they differ from ANSI C rules? Ans: Rules of naming variables in C++ are given below : a.3:Why does C++ have type modifiers? .Chapter 3: 3.2:An unsigned int can be twice as large as the signed int. Digit can be used but not at the beginning. * Here the absolute value of lower value -2m–1 for signed int must be considered for finding average value of signed int. In C all variables must be declared at the beginning of the program. Any character from ‘a’ to ‘z’ or ‘A’ to ‘Z’ can be used. Underscore can be used but space is not permitted. of bit] In case of signed int the range of the input value is : -2m–1 to + (2m–1 – 1) So. maximum value for unsigned int can be twice as large as the signed int. b. d. c. A keyword cannot be used as variable name. Explain how? Ans: In case of unsigned int the range of the input value is : 0 to 2m – 1. [where m is no. 3. Example : void function (void) Another interesting use of void is in the declaration of generic pointers. ECE. Example : void *gp. CSE. // valid. (2) To indicate any empty argument list to a function. The enum keyword automatically enumerates EEE to 0 CSE to 1 ECE to 2 CE to 3 . ME. with examples. Because to assign a pointer to another pointer data type must be matched. CE. We can achieve this using casting. 3. IEM). the uses of enumeration data types. //gp is generic pointer. Ans:An enumerated data type is a user-defined type. 3. gp = ip.6:Describe.Ans: To serve the needs of various situation.4:What are the applications of void data type in C++? Ans: Two normal uses of void are (1) to specify the return type of a function when it is not returning any value.5:Can we assign a void pointer to an int type pointer? If not. A pointer value of any basic data type can be assigned to a generic pointer int * ip. int *ip. why? Now can we achieve this? Ans:We cannot assign a void pointer to an int type pointer directly. Example : void * gp. It provides a way for attaching names to numbers in ANSIC Example : enum kuet (EEE. ip = (int * ) gp /br<> 3. Why? Ans:An additional null character must assign at the end of the string that’s why the size of char array that is declared to store a string should be one larger than the number of characters in the string. Ans:Consider the following example : enum kuet (EEE. so array is called derived data type.ME to 4 IEM to 5 In C++ each enumerated data type retains its own separate type. In C++ tag name become new type name. Example: student cgp = 3. .7:Describe the differences in the implementation of enum data type in ANSI C and C++.01 //OK in C++ 3. 3. The data can be accessed by an index number from o to n. CSE. ECE. CE. Hence an array is derived from the basic date type. ME. Arrays refer to a list of finite number of same data types. But in C++ this is not permitted. IEM). kuet is tag name. 3.8:Why is an army called a derived data type? Ans:Derived data types are the data types which are derived from the fundamental data types. ANSI C defines the types of enum to be int. student cgp = (student) 3. Here. We can declare a new variables Example: kuet student.9:The size of a char array that is declared to store a string should be one larger than the number of characters in the string. In C int value can be automatically converted to on enum value.01 // Error in C++ // OK in C. it defaults to int.11:How does a constant defined by cowl differ from the constant defined by the preprocessor statement %define? Ans:Consider a example : # define PI 3. char name [size]. In C const is global in nature . Ans:In both C and C++. although quite differently. 3. This would be illegal in C. it can be made as local declaring it as static.3. 3. C++ requires const to be initialized.14159 The preprocessor directive # define appearing at the beginning of your program specifies that the identifier PI will be replace by the text 3. In C++ we can use const in a constant expression. In C++ a const is local. However there are some differences in implementation. For example.12:In C++. const size = 10. What is the significance of this feature? Ans:It is very easy to understand the reason of which the variable is declared. ANSI C does not require an initialization if none is given. 3. any value declared as const cannot be modified by the program in any way. Explain. In short.13:What do you mean by dynamic initialization of a variable? Give an example. it initializes the const to o. means const int size = 10. If we use const modifier alone. a variable can be declared anywhere in the scope.14159 throughout the program. const allows us to create typed constants instead of having to use # define to create constants that have no type information. The keyword const (for constant) precedes the data type of a variable specifies that the value of a variable will not be changed throughout the program. such as const int size = 10. . it can be made as global defining it as external.10:The const was taken from C++ and incorporated in ANSI C. Ans: New opperators added by C++ are : 1.Ans:When initialization is done at the time of declaration then it is know as dynamic initialization of variable Example : float area = 3. Memory release operator delete &nbsp delete 3. Field width operator &nbsp setw 5.15:List at least four new operators added by C++ which aid OOP.17:What are the advantages of using new operator as compared to the junction ntallocOr Ans:Advantages of new operator over malloc (): . A major application of reference variables is in passing arguments to functions. 3.14:What is a reference variable? What is its major use? Ans:A reference variable provides an alias (alternative name) for a previously defined variable. 3.16:What is the application of the scope resolution operator :: in C++? Ans:A major application of the scope resolution operator is in the classes to identify the class to which a member function belongs. Line feed operator &nbsp endl 3.14159*rad * rad. Memory allocation operator &nbsp new 4. Scope resolution operator :: 2. 3. Ans: (a) Char * const P.19:How do the following statements differ? (a) char *const p.1 What will happen when you execute the following code? 1 #include <iostream. will print 1 2 3 4 If argument is negative massage will be printed at left justified. In case of (a) we con not modify the address of p. cout <<setw(-10)<< “1234”. how the seize manipulator works. so that there is no need to use a type cast.h> main() 2 void { 3 int i=0.1. We need not use the operator size of. In case of (b) we can not modify the contents of what it points to. means pointer to a constant. For example : setw (10) specifies 10 columns and print the massage at right justified. (b) char canal *p. Like any other operator. . 4. It automatically computes the size of the data object. The number of columns is equal the value of argument of setw () function. 3. It automatically returns the correct pointer type. cout << set (10) << “1234”. 3. will print 1 2 3 4 3. Ans: setw manipulator specifies the number of columns to print. means constant pointer. 2. 3. 4 i=400*400/400. It is possible to initialize the object while creating the memory space. new and delete can be overloaded. (b) Char const * P.18:Illustrate with an example. 2Identify the error in the following program. 4 while(i) { 5 switch(i) 6 { 7 default: 8 case 4: case 5: 9 break. You should write index number after array name but here index number is mention before array name in [1] num So expression syntax error will be shown. to see the correct output. #include <iostream. 16 } 17 } .3 Identify the errors in the following program.2. Here. num[1]==[1]num ? cout<<"Success" : cout<<"Error". 1 2 3 4 5 6 include<iostream. 3. So wrong output will be shown when this program will be run.3. Correction : num[1] = num[1]? is the correct format 3. 12 case 2: 13 case 3: break.5 6 7 cout<<i. 10 case 1: 11 continue. 14 } 15 i-. } Ans: i = 400*400/400. } Ans: num [1] = [1] num?. 400*400 = 160000 which exceeds the maximum value of int variable. Correction : 1 int i = 0.5.6}.h> void main() { int num[]={1. should be changed as 1 long int i = 0.h> 1 void main() 2 { 3 int i=5.4. h> #define pi 3. Correction: At last line i. The above code will cause the following situation: Program will be continuing while value of i is 1 and value of i is updating. 3. So infinite loop will be created. 3.6 Find errors. int circleArea(int &).18 19 20 21 Ans: 1 case 1 : 2 continue. (a) long float x. in the following C++ statements.4 Identify the errors in the following program. { int squareArea(int &a) { return a *== a. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 #include <iostream. cout « circleArea(a) « ".14 int squareArea(int &).should be changed as i–. } int circleArea(int &r) { return r = pi * r * r. That means the above line should be changed as follows: 1 return a *=a. } Ans: Assignment operator should be used in the following line: 1 return a *==a. cout « a « endl. . void main() { int a-10.5 Missing 3. cout << squareArea(a) << " ". if any. (j) wrong data type float *p = new float [10]. (c) No error (d) syntax error (e) tag name missing (f) (g) address have to assign instead of content C++ requires a const to be initialized int*p = new int [10]. i++) cout << i << "/n". red) int const * p = &total. (b) type must be matched char *cp = (char*) vp. . enum colour (green. (g) const int array_size. (k) keyword can not be used as a variable name cout << i << “/n”. yellow. (k) int public = 1000. for (int i = 1. Ans: No. (h) for (i=1. (i) int & number = 100. // three is an enumerator (d) int sp = new. i <10. int i<10. const int array-size = 5. (l) char name[33] = "USA". or double x. // vp is a void pointer (c) int code = three. (j) float *p = new int 1101.(b) char *cp = vp. red). int public1 = 1000. yellow. (f) int const sp = total. // allocate memory with new (e) enum (green. i++) (h) Undefined symbol i (i) invalid variable name int number = 100. Error Correction (a) too many types float x. 10 temp=a. cout<<" After swapping "<<endl 13 <<" a = "<<a<<endl<<" b = "<<b<<endl<<endl. cout<<" Enter two integer value : "<<endl.int &b) 6 { 7 8 cout<<" Before swapping "<<endl <<" a = "<<a<<endl<<" b = "<<b<<endl<<endl. 21 swap_func (x. 20 cin>>x>>y. 9 int temp.1 Write a function using reference variables as arguments to swap the values of a pair of integers. 23 } 24 25 O U T P U T Enter two integer value : 56 61 Before swapping a = 56 b = 61 After swapping .y). 11 a=b.h> 3 #include<iomanip.h> 4 5 void swap_func(int &a. 14 15 16 } 17 int main() 18 { 19 int x.array size of char must be larger (l) than the number of characters in char name [4] = “USA”. Solution: 1 2 #include<iostream. the string 3. 22 return 0.y. 12 b=temp. i++) 16 { 17 18 if(i==m-1) 19 cout<<v[i].h> 3 #include<iomanip. 24 return 0.". 6 int *v.i<m.h> 4 int main() 5 { int m. 25 } 26 27 O U T P U T Enter vector size : 5 to check your performance insert 5 integer value 7 5 9 6 1 Given integer value are : 7. 7 cout<<" Enter vector size : "<<endl. 14 } cout<<" Given integer value are :"<<endl. 9 v=new int [m]. 9. 15 for(i=0. for(int i=0.i<m. 10 cout<<" to check your performance insert "<<m<<" integer 11 value"<<endl. Solution: 1 2 #include<iostream.a = 56 b = 61 3.i++) 12 { 13 cin>>v[i]. 5. 21 22 } 23 cout<<endl. 8 cin>>m. 20 else cout<<v[i]<<".2 Write a function that creates a vector of user given size M using new operator. 1 3.3 Write a program to print the following outputs using for loops . 6. 0.h> 3 #include<iomanip.i++) { 10 for(int j=1. 3000. 8 cout<<endl<<endl.11. 9 for(int i=1.0. r and n: P: 1000.000 r: 0. 16 } 17 18 O U T P U T Enter your desired number : 6 1 22 333 4444 55555 666666 3.i<=n.12.j++) 11 { 12 cout<<i. 7 cin>>n.j<=i.h> 4 int main() { 5 int n. 14 } 15 return 0. 0.…………………. 13 } cout<<endl..20 .4 Write a program to evaluate the following investment equation V = P(1+r)n and print the tables which would give the value of V for various of the following values of P.……………. 6 cout<<" Enter your desired number :"<<endl.10. 2000.1 22 333 4444 55555 ……………… Solution: 1 2 #include<iostream.10. 15.6000.0.h> 3 #include<math. This equation can be recursively written as V = P(1 + r) P=V In other words.11.13.20}. 23 24 v=pf*(1+r[i]). 27 cout..19.0.setf(ios::fixed.0.i<size. 3. 8 int n=size.//.0. 13 cout<<setw(5)<<"n=1". 34 } 35 .0. the value of money at the end of the first year becomes the principal amount for the next year and so on) Solution: 1 #include<iostream. 28 cout<<v<<setw(10).0.i<=size. 25 26 cout. 11 float 12 r[size]={0.pf.j<size. 31 32 } 33 return 0.i++) 18 { 19 cout<<setw(-6)<<"p=".0.7000.h> 2 #include<iomanip.. 20 for(int j=0. 17 for(i=0.10 (Hint: P is the principal amount and V is the value of money at the end of n years.i++) 15 cout<<setw(9)<<"n="<<i.j++) 21 { 22 if(j==0) pf=p[i].2000.5000.//9000.16. 14 for(int i =2.3000.8000}.precision(2).0.n: 1.………………………………….0. ios::floatfield).12.4000.1000}.14.h> 4 #define size 8 5 6 int main() { 7 float v. pf=v. 29 } 30 cout<<"\n". 2. 9 float 10 p[size]={1000.18}. 16 cout<<"\n".17. h> 1 #include<iomanip.29 p=9440 11139.16 4421.68 5527.06 1870.36 37 O U T P U T n=1 p=1110 n=2 n=3 n=4 n=5 n=6 1232.36 7057. 14 15 while(1) { 16 cin>>test. Solution: #include<iostream.41 p=2240 2508.65 6245.37 p=6960 8073.66 8779.31 3947.79 3. the ballot should be considered as a “spoilt ballot” and the program should also count the numbers of “spoilt ballots”.43 25483.38 p=8190 9582.15 21008. 17 18 for(int i=1.i++) 19 { 20 if(test==i) { 21 "<<endl<<" pr .7 21596.3 11211.8 2809.84 7701. a number read is outside the range 1 to 5.89 10009.63 1518.03 10056.82 67 55.i<=5.7 4328.4 5926.3 13300.1 10863.86 3147.32 15347.04 p=3390 3830.i<5.86 n=7 2076.14 18302. The candidates are numbered 1 to 5 and the voting is done by marking the candidate number on the ballot paper.i++) 6 { 7 count[i]=0. Write a program to read the ballots and count the vote cast for each candidate using an array variable count.1 1367.79 11565.5 7604.5 An election is contested by five candidates.26 3524.06 17956. 8 } 9 int spoilt_ballot=0.2 13144.22 12602.07 1685.08 8745.6 9365.84 13117.42 p=4560 5198.69 4891. int test. cout<<" You can vot candidate 1 to 5 "<<endl 10 <<" press 1 or 2 or 3 or 4 or 5 to vote "<<endl 11 <<" candidate 1 or 2 or 3 or 4 or 5 respectively "<<endl 12 <<" press any integer value outside the range 1 to 5 for NO VOTE 13 result :"<<endl.h> 2 int main() 3 { 4 int count[5].18 p=5750 6612.38 16957.21 15510. 5 for(int i=0.05 14618. In case. } O U T P U T You can vot candidate 1 to 5 press 1 or 2 or 3 or 4 or 5 to vote candidate 1 or 2 or 3 or 4 or 5 respectively press any integer value outside the range 1 to S for NO VOTE press any negative value to terminate and see result : 1 1 1 5 4 3 5 5 2 1 3 6 -1 candidate 1 candidate 2 candidat e 3 candidate 4 candidate S 4 1 2 1 3 spoilt_ballot 1 . return 0.k<=5. cout<<endl. cout<<setw(7).k<5. } for(int k=1.k++) cout<<count[k]<<setw(13). cout<<endl.count[i-1]++. for(k=0. cout<<" spoilt_ballot "<<spoilt_ballot<<endl. 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 } } if(test<0) break. else if(test>5) spoilt_ballot++.k++) cout<<" candidate "<<k<<setw(12). 27 28 cin>>name[i]. 12 cin>>n. 15 time_not_out=new int[n]. 13 run=new int[n].h> #include<iomanip.i++) { 18 if(i>2) 19 { 20 cout<<"\n Input details of "<<i+1<<"th"<<" player's"<<endl.6 A cricket has the following table of batting figure for a series of test matches: Player’s name 8430 Run Innings 230 130 Time not outSachin 18Saurav 9Rahul 4200 3350 11. 10 int *time_not_out. 105 . Write a program to read the figures set out in the above forms. to calculate the batting arranges and to print out the complete table including the averages. 24 } 25 26 cout<<" Enter name : ". . 8 int *run." SECOND " . 16 17 for(int i=0. ." THIRD "}.3. 9 int *innings. .//global declaration 5 int main() 6 { 7 int n. 29 cout<<" Enter run : ". . . //name=new char[n]. 14 innings=new int[n].i<n. char name[100][40]. 11 cout<<" How many players' record would you insert ? :". Solution: 1 #include<iostream. .. cin>>run[i]. . 30 . .h> 2 3 4 char *serial[3]={" FIRST ". . 21 } 22 else { 23 cout<<" Input details of "<<serial[i]<<"player's : "<<endl. 809525 5 .i++) 38 { 39 float avrg.i<n. 51} 52 53 54 55 56 57 58 59 O U T P U T How many players record would you insert ? :2 Input details of FIRST player’s : Enter name : Sakib-Al-Hassan Enter run : 1570 Enter innings : 83 Enter times not out : 10 Input details of SECOND player’s : Enter name : Tamim Enter run : 2000 Enter innings : 84 Enter times not out : 5 player’s name run innings Average times not out Sakib-Al-Hassan 1570 83 18. 34 } 35 float *average. 49 50 return 0. 45 for(i=0.cout<<" Enter innings : ". 36 average=new float[n]. 41 } 42 cout<<endl<<endl. 40 average[i]=float(run[i])/innings[i]. 32 cout<<" Enter times not out : ".i<n. 37 for(i=0. 43 cout<<setw(12)<<"player's name "<<setw(11)<<"run"<<setw(12)<<"innings"<<setw(16) 44out"<<endl.915663 10 Tamim 2000 84 23. 33 cin>>time_not_out[i]. 31 cin>>innings[i].i++) { 46 cout<<setw(14)<<name[i]<<setw(11)<<run[i]<<setw(9)<<innings[i]<<setw(18)<<av 47 } 48 cout<<endl. if(x<0) { x=x*(-1).3. } else if(x>270 && x<=360) { ".x.0001% accuracy (a) sinx = x – x3/3! + x5/5! – x7/7! +………… (b) SUM = 1+(1/2)2 + (1/3)3 +(1/4)4 + ……… (c) Cosx = 1 –x2/2! + x4/4! – x6/6! + ……… Solution (a): 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 #include<iostream. int m.0001 #define pi 3.7 Write a program to evaluate the following function to 0.1416. } again: if(x>90 && x<=180) { x=180-x. .h> #include<math. //const float pi=3. d=x. sign=-1.1416 long int fac(int a) { if(a<=1) return 1. int sign. sign=-1.fx. int n=1.y1.h> #define accuracy 0. cout<<" Enter the value of angle in terms of degree: cin>>x. sign=1. float d. } int main() { float y. } else if(x>180 && x<=270) { x=x-180. else return a*fac(a-1).h> #include<iomanip. 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 x=360-x. fx+=y1/h. x=m%360+fractional. float fractional=x-m. m=n+1.) { long int h=fac(n). } else if(x>360) { int m=int(x). for(. n=n+2. } x=(pi/180)*x.. y=pow(x. int factor=pow(-1. fx=0. m++. if(x>90) goto again. else sign=1. y1=y*factor.n). } cout<<"sin("<<d<<")= "<<fx*sign<<endl.m).866027 . } O U T P U T Enter the value of angle in terms of degree: 120 sin(120)= 0. sign=-1. if(y/h<=accuracy) break. return 0. 17 } 18 Sample Output(b) 19 20 Solution: (c) #include<iostream. 27 else 28 return n*fac(n-1).m.0001 23 24 long int fac(int n) 25 { if(n<=1) 26 return 1.1416. 36 const float pi=3.n1.0001 3 int main() 4 { int n. 40 x=(pi/180)*x. cout<<" Enter the value of angle in terms of degree: 37 cin>>x.i). . 38 if(x<0) 39 x=x*(-1). 29 } 30 31 int main() 32 { 33 float y.h> 1 #include<math. 41 42 fx=1.h> 21 22 #include<math.. 9 m=pow(n1. 13 14 n++.h> #define accuracy 0. 16 return 0. 11 if(m<=accuracy) 12 break. 6 n=1. 34 int n=1. } 15 cout<<sum<<"\n".Solution (b): #include<iostream.i++) 8 { n1=float(1)/n.fx. 7 for(int i=1. 35 int m. 10 sum+=m.y1.x. 43 ".sum=0.h> 2 #define accuracy 0. 5 float sum. for(. if(y1/h<=accuracy) break.866025 3. int factor=pow(-1.6 0.h> 2 #include<iomanip.h> 0. } O U T P U T Enter the value of angle in terms of degree: 60 0. 0.0 . } cout<<fx<<"\n".0 Solution: 1 #include<iostream.900 .1. The table should appear as follows TABLE FOR X Y =EXP[-X].4 0. y2=(y1/h)*factor.m).44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 m=2.1 0.8: Write a program to print a table of values of the function Y = e-x For x varying from 0 to 10 in steps of 0. n++.) { h=fac(m). y1=pow(x.2 0..3 0.8 0. fx+=y2.7 0. 9. long int h. float y2.5 1. .n). m=m+2. 13 for(float j=0.036883 0.049787 4 0.k=k+0.006738 0.012277 0.005517 6 0.000304 0.1) cout<<"-".000676 0.67032 0.ios::floatfield). 8 for(float k=0. 19 cout. 20 cout.i<. 25} 26 27 28 29 Note: Here we work with 0. O U T P U T TABLE FOR Y=EXP(-X) x 0 0 1 0.000825 0.013569 0.000101 0.001836 0.j<10.4 for a good looking output.i=i+0.setf(ios::fixed.045049 0.904837 0.h> int main() 4 { 5 float x.7.018316 5 0.000335 9 0. cout<<setw(10)<<y.246597 0. 18 y=exp(-x).014996 0. 10 cout<<"\n".1) 9 cout<<setw(10)<<k.7.002479 0. 12 cout<<"\n".k<10*.000083 3.135335 3 0.000112 0.y.040762 0.000123 0. 21 } 22 cout<<"\n".000611 0.004992 0.j++) 14 { 15 cout<<j<<setw(4).740818 1 0. 11 for(k=0.033373 0.332871 0.1) 16 { 17 x=i+j.k<.016573 0.7.4 0.3 #include<math. for(float i=0.1 0.000225 0. cout<<"x".9 Write a program to calculate the variance and standard deviation of .002243 0.002029 7 0.3 0.100259 0.2 0.090718 0.818731 0.001662 0.006097 0.000249 0.004517 0.k=k+0. 6 cout<<" TABLE FOR Y=EXP(-X) 7 :\n\n".precision(6).000275 0.000912 0.110803 0.272532 0.367879 2 0.122456 0.301194 0.000747 8 0. 23 } 24 return 0.000091 0. float v. 26 cout<<"\n\n variance = "<<variance<<"\n standard deviation = 27 "<<std_deviation<<"\n". 10 float sum. cin>>n.i++) 20 { 21 v=x[i]-mean. 17 mean=sum/n.i<n.h> 4 #include<math. 22 v1+=pow(v. 12 for(int i=0.i<n. } 23 float variance. 29 } 30 31 32 O U T P U T How many number ? :5 10 2 4 15 . 14 sum+=x[i]. 24 variance=v1/n.std_deviation. 15 } 16 float mean. 11 sum=0. 8 int n.h> int main() 5 { 6 float *x. 19 for(i=0. 25 std_deviation=sqrt(variance). 9 x=new float[n]. 7 cout<<" How many number ? :".2).i++) 13 { cin>>x[i]. 18 v1=0.N numbers Variance =1/N ∑(xi -x)2 Standard deviation=√1/N ∑(xi -x)2 Where x = 1/N ∑xi Solution: 1 2 3 #include<iostream. 28 return 0.v1. 21 charge=charge+additional. 24 cout<<" Press o for exit / press 1 to input again :". 17 } 18 else if(unit>300) { 19 charge=50+(90*unit)/float(100). cout<<setw(15)<<name<<setw(20)<<charge<<endl.24 standard deviation = 5.00.10 An electricity board charges the following rates to domestic users to discourage large consumption of energy: For the first 100 units – 60P per unit For the first 200 units – 80P per unit For the first 300 units – 90P per unit All users are charged a minimum of Rs.h> 1 #include<iomanip.2 variance = 26. 50. 10 cin>>name>>unit. Write a program to read the names of users and number of units consumed and print out the charges with names. 300. If the total amount is more than Rs. 27 if(test==1) . 5 char name[40]. Solution: #include<iostream. 22 } 23 cout<<setw(15)<<"Name"<<setw(20)<<"Charge"<<endl. 20 additional=(charge*15)/100. 4 float charge. 25 int test. 6 while(1) 7 8 { 9 input: cout<<" Enter consumer name & unit consumed :".h> 2 int main() 3 { int unit. 14 } else if(unit<=300 && unit>100) 15 { 16 charge=50+(80*unit)/100.additional. 11 if(unit<=100) 12 { 13 charge=50+(60*unit)/100.00 then an additional surcharge of 15% is added. 26 cin>>test.122499 3. } return 0. else if(test==0) break.28 29 30 31 32 33 34 35 36 37 38 39 goto input. } O U T P U T Enter consumer name & unit consumed :sattar 200 Name Charge sattar 210 Press o for exit / press 1 to input again :1 Enter consumer name & unit consumed :santo 300 Nmae Charge santo 290 Press o for exit / press 1 to input again : 0 . 4. float area (float a. (c) When a function returns a value. float b). The prototype describes the function interface to the compiler by giving details such as the number and type of arguments and the type of return values. float area (float. the function works with the original arguments in the calling program. . a temporary variable is created in the calling program to hold the argument value. Ans: General form of function prototyping : return_type function_name (argument_list) Example : int do_something (void).1: State whether the following statements are TRUE or FALSE. (d) A function can return a value by reference. (f) It is not necessary to specify the variable name in the function prototype.Chapter 4: 4. (a) A function argument is a value returned by the function to the calling program. (b) When arguments are passed by value. float). Ans: (a) FALSE (d) TRUE (b) FALSE (e) FALSE (c) TRUE (f) TRUE 4. (e) When an argument is passed by reference.2:What are the advantages of function prototypes in C++? Ans: Function prototyping is one of the major improvements added to C++ functions. the entire function call can be assigned to a variable.3:Describe the different styles of writing prototypes. y (b) Undefined symbol b (c) No error (d) (e) Correction float average (float x.y). Ans: No.4:Find errors. . (e) void print(float data[]. Error (a) Undefined symbol x. int size = 20). (c) int display(…. floaty) int mul (int a. 4. int name &size). By declaring a function inline the execution time can be minimized. (d) void Vect(int? &V.b). 4. in the following function prototypes.5:What is the main advantage of passing arguments by reference? Ans: When we pass arguments by reference. if any.). the formal arguments in the called function become aliases to the ‘actual’ arguments in the calling function. then it is declared as inline function. (b) int mul(int a. int & size). Undefined symbol ‘s’ void print (float data [ ].6:When will you make a function inline? Why? Ans: When a function contains a small number of statements. size = 201).4. int b). invalid character in variable void vect (int &v. (a) float average(x. When we need to design a family of functions-with one function name but with different argument lists. } 4.. 4. return(&m). 4..1416) { return PI*r*r..9: What is the significance of an empty parenthesis in a function declaration? Ans: An empty parentheses implies arguments is void type. } . . the usual error checking does not occur during compilation. float PI = 3... . 4.. Example : 1 2 3 4 Float area (float r...4. then it is needed to assign a default value to the parameter. But using inline-function this problem can be solved.7:How does an inline function differ from a preprocessor macro? Ans: The macos are not really functions and therefore. then we use this concept.11: Comment on the following function definitions: (a) 1 2 3 4 5 6 int *f( ) { int m = 1.8:When do we need to use default arguments in a function? Ans: When some constant values are used in a user defined function.10:What do you meant by overloading of a function? When do we use this concept? Ans: Overloading of a function means the use of the same thing for different purposes. . } . 1 2 3 4 5 6 7 8 9 10 11 12 13 #include <iostream..10. return(n)........ } void main() { cout <<(int)fun() << ' '. .7 (b) 1 2 3 4 5 6 double f( ) { . return(1).. This function returns 1 after execution.. (a) (b) (c) Comment This function returns address of m after execution this function...h> int fun() { return 1. } float fun() { return 10..23. cout << (float)fun() << ' '. } Ans: No.... returns address of n 4. . } (c) 1 2 3 4 5 6 7 int & f() { int n .1: Identify the error in the following program. cout <<arrayl[i]<< ' ' << array2[i] << ' ' .h> int fun() { return 1. for(int 1=0. } void main() { cout<<fun()<<" ".14 Solution: Here two function are same except return type. 1++) { arrayl[i] = i. i<5.23. int arrayl[constl]. Correction : This error can be solved as follows : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 #include<iostream. } 4. } . Function overloading can be used using different argument type but not return type. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 #include <iostream. array2[i] = i*10. } } void main() { display(5). } float fun1() { return 10. cout<<fun1()<<" ". int array2[const2].2: Identify the error in the following program.h> void display(const Int constl=5) { const int const2=5. void extra() { cout << gValue << ' '. 8 int array2[const2].h> int gValue=10. 7 int array1[const1]. cout << : gValue << ' '. 9 10 for(int i=0.i++) 11 { array1[i]=i. 12 array2[i]=i*10. .Solution: 1 2 #include<iostream. { int gValue = 20.h> 3 4 void display() 5 { const int const1=5. 6 const int const2=5. 19 } 20 21 "<<array2[i]<<" 4.i<5.3: Identify the error in the following program. } void main() { extra(). } } ". 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 #include <iostream. cout << gValue << ' '. 13 cout<<array1[i]<<" 14 } 15 } 16 17 void main() 18 { display(). if any. . replace with cout <<::gvalue<< " ". 4. } Solution: First dimension of an array may be variable but others must be constant. cout << gValue << ‘ ‘. int A[10] [10]. Here int A [ ] [ ] replace by the following code: int A [ ] [10]. j<n. int n) 1 2 3 4 5 6 { for(1=0.4: Find errors. cout<<"\n". Where const int size = 100.Solution: Here cout << : gvalue << " ". int m. void extra() { cout << gValue << ‘ ‘. i++) for(j=o. { int gValue = 20. int A[ ] [size]. in the following function definition for displaying a matrix: void display(int A[][]. i<m. cout <<::gvalue<< " ". any other numerical value can be assigned to size.1: Write a function to read a matrix of size m*n from the keyboard. } } 4. j++) cout<<" "<<A[i][j].h> int gValue=10. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 #include <iostream. int A [size] [size]. } void main() { extra(). j<n. 36 return 0.int n) 7 { 8 float **p. for(i=0.j++) 17 { float value.h> 4 #include<iomanip.i<m.i<m. } 27 cout<<"\n". 20 } 21 } 22 cout<<" The given matrix is :"<<endl. 35 matrix(r. p=new float*[m].i++) 10 { 11 p[i]=new float[n].i<m. 28 } 29 } 30 31 int main() 32 { int r. 33 cout<<" Enter size of matrix : ". 12 } 13 cout<<" Enter "<<m<<"by"<<n<<" matrix elements one by one 14 "<<endl.Solution: 1 2 3 #include<iostream. 34 cin>>r>>c. for(i=0.i++) 15 { 16 for(int j=0. 9 for(int i=0. 37 } 38 39 40 O U T P U T Enter size of matrix : 3 4 Enter 3 by 4 matrix elements one by one 1 2 3 4 . 19 p[i][j]=value.c). 18 cin>>value.j++) 25 { 26 cout<<p[i][j]<<" ".i++) 23 { 24 for(int j=0.c.j<n.h> 5 6 void matrix(int m. 20 for(i=0. 9 } 10 cout<<" Enter "<<m<<" by "<<n<<" matrix elements one by one 11 "<<endl. p[i][j]=value.h> #include<iomanip. Solution: 1 #include<iostream.h> 2 3 void matrix(int m. for(int i=0.2: Write a program to read a matrix of size m*n from the keyboard and display the same on the screen using function.i<m.2 3 4 5 3 4 5 6 The given matrix is : 1 2 3 4 2 3 4 5 3 4 5 6 4.i<m.j<n. 31 cin>>r>>c. } 26 27 } 28 int main() 29 { 30 int r.c.j++) 14 { 15 float value. 16 cin>>value. cout<<" Enter size of matrix : ".i++) 12 { 13 for(int j=0. 32 .j<n.int n) 4 { 5 float **p.i++) { 21 for(int j=0.j++) 22 { 23 cout<<p[i][j]<<" ". 17 } 18 } 19 cout<<" The given matrix is :"<<endl.i<m.i++) 7 { 8 p[i]=new float[n]. 24 } 25 cout<<"\n". 6 p=new float*[m]. for(i=0. p=new float*[m].matrix(r.i++) { p[i]=new float[n].i++) . Solution: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 #include<iostream. p[i][j]=value.i<m.c). for(i=0.3: Rewrite the program of Exercise 4. } cout<<" Enter "<<m<<" by "<<n<<" matrix elements one by one "<<endl.i<m.j++) { float value.int m=3) { float **p. for(int i=0.h> void matrix(int n. cin>>value.h> #include<iomanip. return 0.2 to make the row parameter of the matrix as a default argument. 33 34 35 36 37 38 39 40 } O U T P U T Enter size of matrix : 4 4 Enter 4 by 4 matrix elements one by one 1 2 3 4 7 2 3 4 5 8 3 4 5 6 9 The given matrix is : 1 2 3 4 7 2 3 4 5 8 3 4 5 6 9 4. } } cout<<" The given matrix is :"<<endl.i<m.i++) { for(int j=0.j<n. for(i=0. i++) .h> void matrix(int m. cin>>c. Discuss with examples. Solution: 1 2 3 4 5 6 #include<iostream. ".4: The effect of a default argument can be alternatively achieved by overloading.j<n. p=new float*[m]. cout<<" Enter column of matrix : ".i<m. return 0. matrix(c).h> #include<iomanip. for(int i=0.int n) { float **p.j++) { cout<<p[i][j]<<" } cout<<"\n". } O U T P U T Enter column of matrix : 3 Enter 3 by 3 matrix elements one by one 1 2 3 2 3 4 3 4 5 The given matrix is : 1 2 3 2 3 4 3 4 5 4.{ 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 for(int j=0. } } int main() { int c. } } void matrix(int m. for(i=0.i++) { for(int j=0.i++) { for(int j=0. p[i][j]=value.long int n=3) { float **p. cin>>value.i<m.i<m.j<n. } } int main() .j++) { cout<<p[i][j]<<" ". } } cout<<" The given matrix is :"<<endl.i<m.i++) { p[i]=new float[n].j++) { cout<<p[i][j]<<" ". for(int i=0.i++) { for(int j=0.j<n.j++) { float value. p=new float*[m]. } cout<<" Enter "<<m<<"by"<<n<<" matrix elements one by one "<<endl. } cout<<" Enter "<<m<<" by "<<n<<" matrix elements one by one "<<endl. cin>>value. } cout<<"\n".i<m. p[i][j]=value. } cout<<"\n". for(i=0. for(i=0.i<m.j<n. for(i=0.7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 { p[i]=new float[n].j<n.j++) { float value.i++) { for(int j=0. } } cout<<" The given matrix is :"<<endl. if(a>b) 6 { 7 if(a>c) 8 largest=a.float c) 4 { 5 float largest.h> 1 #include<iomanip.float b.h> 2 3 float large(float a. cout<<" Enter row of matrix : ". matrix(r).{ 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 int r.5: Write a macro that obtains the largest of the three numbers. } 11 else 12 { 13 if(b>c) 14 largest=b. } O U T P U T Enter column of matrix : 2 Enter 2 by 3 matrix elements one by one 1 0 1 0 2 1 The given matrix is : 1 0 1 0 2 1 4. 9 else 10 largest=c. cin>>r. Solution: #include<iostream. return 0. . } O U T P U T Enter three values : 4 5 8 large = 8 4. 7 } . float largest=large(x.z. } int main() { float x. cout<<" Enter three values : ".z).16 using inline function.15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 else largest=c. 6 return mn.h> 1 #include<iomanip.h> 3 4 long double power(double m.6: Redo Exercise 4. Write a main that gets the values of m and n from the user to test the function.7: Write a function power() to raise a number m to power n. return 0.int n) { 5 long double mn=pow(m.h> 2 #include<math.y. Solution: #include<iostream.n). Use a default value of 2 for n to make the function to calculate the squares when this argument is omitted. The function takes a double value for m and int value for n and returns the result correctly. } return largest. Test the function using a main function. Solution: Blank 4.y. cout<<" large = "<<largest<<endl. cin>>x>>y>>z. cout<<" m to power n : "<<mn<<endl. } O U T P U T Enter the value of m & n 12 6 m to power n : 2985984 m to power n: 144 4.n). return mn. double m. Use a default value of 2 for n to make the function to calculate the squares when this argument is omitted. Write a main that gets the values of m and n from the user to test the function. } int main() { long double mn.h> . return 0.n). mn=power(m.h> 1 #include<iomanip. Solution: #include<iostream. cin>>m>>n. Solution: Blank 4.h> 2 #include<math.6: Redo Exercise 4.long int n=2) { long double mn=pow(m. The function takes a double value for m and int value for n and returns the result correctly. mn=power(m). Test the function using a main function. cout<<" Enter the value of m & n"<<endl.8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 long double power(double m. int n.16 using inline function. cout<<" m to power n : "<<mn<<endl.7: Write a function power() to raise a number m to power n. h> 1 #include<iomanip. Write a main that calls both the functions. cin>>m>>n.h> 3 4 long double power(int m. Both the functions should have the same name.h> 2 #include<math.3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 long double power(double m. cout<<" Enter the value of m & n"<<endl.int n) { long double mn=pow(m. mn=power(m). double m. Solution: #include<iostream.18 but takes an int value for m. return 0.8: Write a function that performs the same operation as that of Exercise 4.int n) 5 { long double mn= (long double)pow(m. cout<<" m to power n : "<<mn<<endl. return mn.n).long int n=2) { long double mn=pow(m. mn=power(m.n). int n.n). } long double power(double m.n). cout<<" m to power n : "<<mn<<endl. } int main() { long double mn. return mn. Use the concept of function overloading. 6 . } O U T P U T Enter the value of m & n 12 6 m to power n : 2985984 m to power n: 144 4. return mn. int m. } int main() { long double mn. int n. cout<<" Enter the value of m & n"<<endl. } O U T P U T Enter the value of m & n 15 16 m to power n : 6. cout<<" m to power n : "<<mn<<endl. } long double power(int m. mn=power(m).n). mn=power(m. cout<<" m to power n : "<<mn<<endl.7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 return mn. return 0.long int n=2) { long double mn=(long double)pow(m.568408e+18 m to power n: 225 .n). cin>>m>>n. The difference is that all declarations inside a structure are default public. 5. here mango is a object. 5. int a.4: What are objects? How are they created? Ans: Object is a member of class. We can create an object as follows: fruit mango. . here a is a variable of int type. Let us consider a simple example.3: How does a C++ structure differ from a C++ class? Ans: Initially (in C) a structure was used to bundle different of data types together to perform a particular functionality C++ extended the structure to contain functions also. In class we can declare a data as private for which the functions outside the class can not access the data and thus if  accomplish data hiding.1: How do structures in C and C++ differ? Ans: C structure member functions are not permitted but in C++ member functions are permitted.2: What is a class? How does it accomplish data hiding? Ans: A class is a way to bind the data and its associated functions together. { } here fruit is the class-name. 5.Chapter 5: 5. Again consider class fruit. h> void f() { cout<<"Outside Of class \n". how are they distinguished? If no.5. } }. void main() { f(). } class santo { public: void f() { cout<<"Inside of class \n". Outside the class definition : general form: return-type class-name : function-name (argument list) { function body } 5.6: Can we use the same function name for a member function of a class and an outside function in the same program file? If yes. The following example illustrates this: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 #include<iostream. robin. We can distinguish them during calling to main ( ) function. } .5: How is a member function of a class defined? Ans: member function of a class can be defined in two places: * Outside the class definition. * Inside the class definition. Inside the class definition : same as other normal function.f(). // outside f() is calling. Ans: Yes. // Inside f() is calling. give reasons. santo robin. cout<<" Now member function 'display()' of class a is calling from class b \n".display(). cout<<" x = "<<s. } }. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 #include<iostream.20 21 5.display().7: Describe the mechanism of accessing data members and member functions in the following cases: (a) Inside the main program.x<<"\n". class b { public: void display() { a s. Ans: (a) Using object and dot membership operator. (c) Inside a member function of another class. x=111. s. void display() { cout<<"This is class a \n". // billal is a object of class b. (b) Just like accessing a local variable of a function. void main() { b billal. } }. (b) Inside a member function of the same class. billal.h> class a { public: int x. The following example explains how to access data members and member functions inside a member function of another class. } . (c) Using object and dot membership operator. (f) Class members are public by default. Ans: (a) FALSE .10: State whether the following statements are TRUE or FALSE.29 30 5. 5. We can access the members without inheriting the class. 5. then it is called friend function. (j) Data members can be initialized inside class specifier. demerits : Maximum size of the memory will occupied by objects according to the size of friend members. (i) Functions cannot return class objects. Merits : We can access the other class members in our class if we use friend keyword.8: When do we declare a member of a class static? Ans: When we need a new context of a variable the n we declare this variable as static. (g) Friend junctions have access to only public members of a class. (e) Classes can bring together all aspects of an entity in one place. (d) Member functions defined inside a class specifier become inline functions by default.9: What is a friend function? What are the merits and demerits of using friend functions? Ans: A function that acts as a bridge among different classes. (b) A function designed as private is accessible only to member functions of that class. (c) A function designed as public can be accessed like any other ordinary functions. (h) An entire class can be made a friend of another class. (a) Data items in a class must always be private. int length.(b) TRUE (c) FALSE *A function designed as public can be accessed like any other ordinary functions from the member function of same class. int l) { width = w. int length. 7 . int h) 5 { width = w.1: Identify the error in the following program 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 #include <iosream.4). } Solution: Void setvalue (in w.h> struct Room { int width. 5.2: Identify the error in the following program 1 #include <iosream. 6 length = h. void setValue(int w. void main() { Room objRoom.h> class Room 2 { 3 int width. int l) function must be public. } }. length = l. objRoom. 4 void setValue(int w. (d) TRUE (e) TRUE (f) FALSE (g) FALSE (h) TRUE (i) FALSE (j) FALSE 5. 1.setValue(12. } }.width=12. Item objltem2. } int getCount() { return count.getCount() << ' '. public: Item() { count++. cout << objlteml. cout << objltem2. cout << objltem2.getCountAddress() << ' '.h> class Item { private: static int count.3: Identify the error in the following program 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 #include <iosream. 5. void main() { Item objlteml.getCount() << ' '. } int* getCountAddress() { return count. objRoom. } Solution: Void setvalue (int w.getCountAddress() << ' '. cout << objlteml. int l) function must be public. } . void main() { Room objRoom. int Item::count = 0.8 9 10 11 12 13 14 15 } }. so here obj1. } }.h> class staticfunction { static int count. 5. } Solution: setCount ( ) is a void argument type. obj1setcount(5).setcount( ). void main() { staticFunction obj1.setCount (5).4: Identify the error in the following program 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 #include <iosream.displayCount(). int staticFunction::count = 10. replace with obj1. public: static void setCounto() { count++. } void displayCount() { cout << count. obj1. 5. 4 } 5 Note: All other code remain unchanged.Solution: 1 2 int* getCountAddress ( ) 3 { return &count.5: Identify the error in the following program 1 #include <iosream. staticFunction::setCount().h> class Length 2 { 3 . Length objLenngth1(5. 1. } Length(int f. float inches. } . cout << objLength1. } }.4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 int feet.5). cout << objLenth1. public: Length() { feet = 5. inches = 6.getInches() << ' '. inches=in.inches-=12.0. } Length addLength(Length 1) { 1. } return 1.feet += this->feet.getFeet() << ' '. 1. } int getFeet() { return feet. 6.inches this->inches. if(1. } float getInches() { return inches.addLength(objLength2).feet++. float in) { feet = f.inches>12) { 1. objLength1 = objLength1. void main() { Length objLength1. } . } 5. Room objRoom2.5). height.Solution: Just write the main function like this: 1 2 3 4 5 6 7 8 9 10 11 #include<iostream.getFeet()<<" ". } void main() { Area().getInches()<<" ". } void displayvalues() { cout << (float)width << ' ' << (float)height. objRoom1. } }. objRoom1.setValue(12. height.h> class Room void Area() { int width.h> void main() { Length objLength1. int h) { width = w. height = h. Length objLength2(5. cout<<objLength1. 8).6: Identify the error in the following program 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 #include <iosream.displayvalues(). public: void setvalue(int w. objLength1=objLength1. cout<<objLength1.6. class Room { int width. Room objRoom1.addLenghth(objLenghth2). public: int assign(void). 2. Include the following members: Data members: 1. Balance amount in the account. Member functions: 1. char ac_type[20]. To assign initial values. 4. 3. Solution: #include<iostream.h> 1 2 3 4 #include<iomanip. . To withdraw an amount after checking the balance.h> class bank { char name[40]. Account number. Write a main program to test the program. Name of the depositor. } 5. 5 6 7 8 9 int ac_no. To display the name and balance.1: Define a class to represent a bank account. Type of account. double balance. 2. 4.Solution: Undefined structure Room in main ( ) function. 3. Correction : Change the main ( ) Function as follow: 1 2 3 4 void main() { Area(). To deposit an amount. 12 13 }. int test. 27 28 cout<<" Enter name .10 void deposite(float b). void display(void).account number & account type to creat account : \n". 14 int bank::assign(void) 15 { 16 float initial. cin>>name>>ac_no>>ac_type. 29 } 30 else 31 . 23 if(test==1) 24 { 25 initial=500. 26 balance=initial. 17 cout<<" You have to pay 500 TK to open your account \n" 18 <<" You have to store at least 500 TK to keep your account active\n" 19 <<"Would you want to open a account????\n" 20 <<" If Yes press 1 \n" 21 <<" If No press 0 : ". 22 cin>>test.// do nothing 32 33 34 return test. . 11 void withdraw(float c). 53 54 } 55 int main() 56 { 57 bank account.35 } 36 void bank::deposite(float b) 37 { balance+=b. 58 59 int t. 38 } 39 void bank::withdraw(float c) 40 { 41 balance-=c. . cout<<setw(12)<<name<<setw(17)<<ac_type<<setw(14)<<balance<<endl. 47 } 48 49 } void bank::display(void) 50 51 52 { cout<<setw(12)<<"Name"<<setw(20)<<"Account type"<<setw(12)<<"Balance"<<endl. 42 if(balance<500) 43 { 44 cout<<" Sorry your balance is not sufficient to withdraw "<<c<<"TK\n" 45 46 <<" You have to store at least 500 TK to keep your account active\n". balance+=c. 60 t=account. 67 account. float wd. 61 if(t==1) { 62 cout<<" Would you want to deposite: ?"<<endl 63 <<"If NO press 0(zero)"<<endl 64 <<"If YES enter deposite ammount :"<<endl. 72 account. 74 account. 75 } 76 else if(t==0) 77 cout<<" Thank you . 73 cout<<" see details :"<<endl<<endl. 65 float dp.deposite(dp).see again\n". 78 return 0.display(). 71 cin>>wd. 66 cin>>dp. 79 80 81 82 83 84 } . 68 cout<<" Would you want to withdraw : ?"<<endl 69 <<"If NO press 0(zero)"<<endl 70 <<"If YES enter withdrawal ammount :"<<endl.withdraw(wd).assign(). 7 void set_element(int i.85 O U T P U T You have to pay 500 TK to open your account You have to store at least 500 TK to keep your account active W ould you want to open a account???? If Yes press 1 If No press 0 : 0 Thank you .h> 2 3 class vector { 4 float *p. 10 void display(void).see again 5. 8 void modify(void). Solution: #include<iostream. 9 void multiply(float b). (d) To display the vector in the form (10. (c) To multiply by a scalar value. (b) To modify the value of a given element. Include member functions to perform the following tasks: (a) To create the vector. 11 12 }. .h> 1 #include<iomanip. 6 public: void creat_vector(int a). 20. 30 …) Write a program to test your class. 5 int size.float value).2: Write a class to represent a vector (a series of float values). 32 else 33 cout<<p[i]<<" .i++) 29 { 30 if(i==size-1) 31 cout<<p[i].13 void vector::creat_vector(int a) 14 { size=a. 34 } 35 cout<<")"<<endl.float value) 18 { 19 p[i]=value. 28 for(int i=0.i<size. 15 p=new float[size]. ". 16 } 17 void vector::set_element(int i. 36 } 37 .i<size.i++) 23 p[i]=b*p[i]. 24 25 } void vector:: display(void) 26 { 27 cout<<"p["<<size<<"] = ( ". 20 } 21 void vector :: multiply(float b) 22 { for(int i=0. 42 cin>>i. 47 p[i]=v. 57 } 58 size--. 50 cout<<" to delete an element enter position of the element :". 44 cout<<" Now enter new value of "<<i+1<<"th 45 element : ". 60 display(). 51 cin>>i. 59 cout<<" New contents : "<<endl. float v.j<size. 41 cout<<" to edit a given element enter position of the element : ". 53 54 for(int j=i. 49 display(). 46 cin>>v. 61 62 } . 48 cout<<" Now new contents : "<<endl.j++) 55 { 56 p[j]=p[j+1]. 52 i--.38 39 void vector::modify(void) 40 { int i. 43 i--. 69 cout<<" enter "<<s<<" elements 70 for(int i=0. float m. 83 santo. 74 } 75 cout<<" Now contents :"<<endl.63 int main() 64 { vector santo. 81 cout<<" Now contents : "<<endl. one by one :"<<endl. 65 int s. } . 80 santo.modify(). 67 cin>>s.display(). santo. 66 cout<<" enter size of vector : ".v). 77 78 cout<<" to multiply this vector by a scalar quantity enter this scalar quantity : ". 79 cin>>m.i++) 71 { 72 float v. 68 santo.set_element(i. 76 santo.display().multiply(m).creat_vector(s). 82 santo. 84 85 86 87 return 0. 73 cin>>v.i<s. 88 89 90 91 92 93 O U T P U T enter size of vector : 5 enter 5 elements one by one : 11 22 33 44 55 Now contents p[5] = ( 11 , 22 , 33 , 44 , 55) to multiply this vector by a scalar quantity enter this scalar quantity : 2 Now contents : p[5] = ( 22 , 44 , 66 , 88 , 110) to edit a given element enter position of the element : 3 Now enter new value of 3th element : 100 Now new contents : p[5] = ( 22 , 44 , 100 , 88 , 110) to delete an element enter position of the element :2 New contents : p[4] = ( 22 , 100 , 88 , 110) 5.3: Modify the class and the program of Exercise 5.1 for handling 10 customers. Solution: #include<iostream.h> 1 2 3 4 #include<iomanip.h> #define size 10 char *serial[size]={" FIRST "," SECOND "," THIRD "," 4th "," 5th "," 6th "," 7th "," 8 ","10th"}; 5 6 class bank { 7 char name[40]; 8 int ac_no; 9 char ac_type[20]; double balance; 10 11 public: int assign(void); 12 void deposit(float b); 13 void withdraw(float c); 14 void displayon(void); 15 16 void displayoff(void); }; 17 18 int bank::assign(void) 19 { 20 21 float initial; cout<<" You have to pay 500 TK to open your account \n" <<" You have to store at least 500 TK to keep your account active\n" 22 <<"Would you want to open a account????\n" 23 24 <<" If Yes press 1 \n" <<" If No press 0 : "; 25 int test; 26 cin>>test; 27 if(test==1) 28 { initial=500; 29 balance=initial; 30 31 cout<<" Enter name ,account number & account type to create account : \n"; cin>>name>>ac_no>>ac_type; 32 } 33 else 34 ;// do nothing 35 return test; 36 37 38 39 } void bank::deposit(float b) { 40 balance+=b; 41 42 43 } void bank::withdraw(float c) { 44 balance-=c; 45 if(balance<500) 46 { cout<<" Sorry your balance is not sufficient to withdraw "<<c<<"TK\n" 47 <<" You have to store at least 500 TK to keep your account active\n"; 48 balance+=c; 49 } 50 51 52 } void bank::displayon(void) { 53 cout<<setw(12)<<name<<setw(17)<<ac_type<<setw(14)<<balance<<endl; 54 } 55 void bank::displayoff(void) 56 { 57 cout<<” Account has not created”<<endl; int main() } 58 59 { bank account[size]; int t[10]; 60 61 62 for(int i=0;i<size;i++) { cout<<" Enter information for "<<serial[i]<<"customer : "<<endl; 63 t[i]=account[i].assign(); 64 if(t[i]==1) 65 { 66 cout<<" Would you want to deposit: ?"<<endl 67 <<"If NO press 0(zero)"<<endl 68 <<"If YES enter deposit amount :"<<endl; 69 float dp; cin>>dp; 70 account[i].deposit(dp); 71 cout<<" Would you want to with draw : ?"<<endl 72 <<"If NO press 0(zero)"<<endl 73 <<"If YES enter withdrawal amount :"<<endl; 74 float wd; 75 cin>>wd; 76 account[i].withdraw(wd); 77 cout<<endl<<endl; 78 } 79 else if(t[i]==0) cout<<”Thank 80 81 82 } you , see again \n”; i<size. 93 } 94 return 0. 95 } 96 97 98 99 100 101 102 103 104 Note: Here we will show output only for Three customers. 91 else if(t[i]==0) 92 account[i].displayoff(). O U T P U T Enter information for FIRST customer : You have to pay 500 TR to open your account .i++) 88 { 89 if(t[i]==1) 90 account[i].83 84 cout<<" see details :"<<endl<<endl.displayon(). But when you run this program you can see output for 10 customer. 86 87 for(i=0. 85 cout<<setw(12)<<"Name"<<setw(20)<<"Account type" <<setw(12)<<"Balance"<<endl. see again Enter information for SECOND customer : You have to pay 500 TR to open your account You have to store at least 500 TR to keep your account active W ould you want to open a account???? If Yes press 1 If No press 0 : 1 Enter name .account numbe r & account type to create account : Billal 11123 fixed W ould you want to deposit: ? If HO press 0(zero) If YES enter deposit amount : 1000000 W ould you want to with draw : ? If HO press 0(zero) If YES enter withdrawal amount : 100000 see details : Name Account type Balance Account has not created Robin saving 500 .You have to store at least 500 TR to keep your account active W ould you want to open a account???? If Yes press 1 If No press 0 : 0 Thank you .account number & account type to create account : Robin 11123 saving W ould you want to deposit: ? If HO press 0(zero) If YES enter deposit amount : 0 W ould you want to with draw : ? If HO press 0(zero) If YES enter withdrawal amount : 0 Enter information for 3rd customer : You have to pay 500 TK to open your account You have to store at least 500 TK to keep your account active W ould you want to open a account???? If Yes press 1 If No press 0 : 1 Enter name . 6 7 public: 8 void creat_vector(void).float value) { 18 19 p[i]=value. void vector::creat_vector(void) { p=new float[size].h> 1 2 3 #include<iomanip. 9 void set_element(int i.12 such that the program would be able to add two vectors and display the resultant vector.vector v2). (Note that we can pass objects as function arguments) Solution: #include<iostream.h> #define size 8 class vector 4 { 5 float *p. 15 } 16 17 void vector::set_element(int i.Billal fixed 900500 5.4: Modify the class and the program of Exercise 5.float value). 10 friend void add(vector v1. } . 11 12 13 14 }. 20 void add(vector v1. 44 for(int i=0.p[i]. 34 35 } 36 37 int main() 38 39 { vector x1. 41 x2.x3. 24 sum= new float[size].i<size.vector v2) 21 { 22 float *sum. 43 cout<<" Enter "<<size<<" elements of FIRST vector : ".p[i]+v2. 25 26 for(int i=0. ".x2.i++) 27 { 28 sum[i]=v1. 23 cout<<"sum["<<size<<"] = (". else 31 cout<<sum[i]<<" .i<size.i++) . 42 x3. 40 x1.creat_vector(). 32 } 33 cout<<")"<<endl.creat_vector(). 29 if(i==size-1) 30 cout<<sum[i].creat_vector(). i++) 52 { 53 float v.i<size. 47 x1. 6 .v).set_element(i.5: Create two classes DM and DB which store the value of distances. 9 . 46 cin>>v. DM stores .{ 45 float v. 57 58 return 0. } 56 add(x1. 9 . 54 cin>>v.set_element(i. 48 } 49 50 cout<<" Enter "<<size<<" elements of SECOND vector : ". 51 for(i=0. 55 x2.x2).v). 17) 5. 59 } 60 61 62 63 64 65 O U T P U T Enter 8 elements of FIRST vector : 4 7 8 2 4 3 2 9 Enter 8 elements of SECOND vector : 1 2 3 4 5 6 7 8 sum[8] = (5 . 11 . 9 . 9 . The display should be in the format of feet and inches or meters and centimeters depending on the object on display. 13 public: 14 void store(float y){d1=y. Write a program that can read values for the class objects and add one object of DM with another object of DB. class DM 4 { 5 float d. 6 public: 7 void store(float x){d=x.} 15 friend void sum(DM. 10 11 12 }.DB).distances in meters and centimeters and DB in feet and inches. .DB). Use a friend function to carry out the addition operation. The object that stores the results may be a DM object or DB object.} 8 friend void sum(DM. Solution: #include<iostream.3048 class DB. 9 void show(). depending on the units in which the results are required. 16 17 18 void show(). }. class DB { float d1.h> 1 2 3 #define factor 0. store(f). 42 43 cout<<" press 1 to display result in meter\n" . float f.store(sum). 39 40 m1. 36 f=sum/factor. 33 34 35 sum=m. 38 DB b1.d1*factor. 37 DM m1. 41 b1.19 void DM::show() 20 { 21 22 cout<<"\n Distance = "<<d<<" meter or "<<d*100<<" centimeter\n". 23 } 24 25 void DB::show() 26 { 27 cout<<"\n Distance = "<<d1<<" feet or "<<d1*12<<" inches \n".DB b) { 31 32 float sum. 28 29 30 } void sum(DM m.d+b. 5). 61 db.db).3). 50 else if(test==2) 51 b1.show().store(10. int test.show(). 59 DB db. } . 46 cin>>test. 62 sum(dm. 47 48 if(test==1) 49 m1.store(12. 52 53 54 } 55 56 57 int main() 58 { DM dm. 60 dm. 63 64 65 66 67 68 return 0.44 <<" press 2 to display result in feet \n" 45 <<" What is your option ? : ". 69 O U T P U T Press 1 to display result in meter Press 2 to display result in feet W hat is your option ? 1 Distance = 14.903931 centimeter .24904 meter or 1424. They do not have return type. It is not mandatory to use constructor in a class. 6. 6. Ans:Yes. 4. 6. Constructors cannot be virtual. They cannot be inherited. 5. they can have default arguments. They are invoked automatically when the objects are created. we have when we need to overload the constructor.Chapter 6: 6.1: What is a constructor? Is it mandatory to use constructors in a class? Ans:A constructor is a ‘special’ member function whose task is to initialize the object of its class.3: List some of the special properties of the constructor functions. 2. 6. Like other C++ functions. 3. They should be declared in the public section. explain the need for such a situation. then we have to do this. not even void. .5: Can we have more than one constructors in a class? If yes. 6.4: What is a parameterized constructor? Ans:The constructors that can take arguments are called parameterized constructors. Ans:Special properties of the constructor functions: 1.2: How do we invoke a constructor function? Ans:Constructor function are invoked automatically when the objects are created. into q.9: Describe the importance of destructors. like other member functions. . It three int type value are passed then santo (int p. float r) is invoked. int r).8: Distinguish between the following two statements: time T2(T1). time T2 = T1. 6. santo (int p. ==> implicitly called of copy constructor. Ans: time T2 (T1). int q. 6. int q. T1 and T2 are objects of time class. 6.10: State whether the following statements are TRUE or FALSE. (a) Constructors. can be declared anywhere in the class. It two int type value and one float type value are passed then sant (int p. Consider following constructor: santo (int p.6. int r) is invoked. One advantage of dynamic initialization is that we can provide various initialization formats using overloaded constructors. ==> explicitly called of copy constructor time T2 = T1.6: What do you mean by dynamic initialization of objects? Why do we need to this? Ans:Initializing value of object during run time is called dynamic initialization of objects. float r). 6. Ans:Destructors are important to release memory space for future use.7: How is dynamic initialization of objects achieved? Ans:Appropriate function of a object is invoked during run-time and thus dynamic initialization of object is achieved. int q. h> class Room { int length. Ans: (a) FALSE (b) TRUE (c) TRUE (d) TRUE (e) TRUE 6. Room objRoom2(12.(b) Constructors do not return any values. (e) Destructors never take any argument. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 #include <iostream. (d) A class should have at least one constructor. length(1) { } }. void main() { Room objRooml. } 1 </br> <span class="a">Solution:</span>Here there is no default constructor.1: Identify the error in the following program. 8). }. so object could any argument. <strong>Correction :</strong> 1 Void main ( ) { Room Objroom2(12. (c) A constructor that accepts no parameter is known as the default constructor. . int width. public: Room(int 1.8). int w=0): width(w). public: Room() { length=0. } Room(int value=8) { length = width =8.3: Identify the error in the following program.h> class Room { int length. objRoom1. 8 height=8. #include <iostream.display(). void main() { Room objRooml. 5 public: void Room() 6 { 7 width=12. width=0.2: Identify the error in the following program. 4 int height. } }. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 #include <iostream. Correction : Erase Room() function and then error will not show.6. int width. 9 } 10 Room(Room& r) . } void display() { cout<<length<< ' ' <<width. so it show Ambiguity error. Solution:Room() and Room(int value=8) Functions are same. 6.h> 1 class Room 2 { 3 int width. 10 } 11 Room(Room& r) { 12 width =r. } }. 4 int height. 1 #include <iostream. Room objRoom4. 9 height=8. } Solution: Just erase “objRoom4 = objRoom3. 14 copyConsCount++. 6 public: void Room() 7 { 8 width=12. invalid to call copy constructor. 6. void main() { Room objRooml. Room objroom2(objRoom1). 5 static int copyConsCount.width.4: Identify the error in the following program. objRoom4 = objRoom3.11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 { width =r. Room objRoom3 = objRoom1.width. int Room::copyConsCount = 0.height.dicopyConsCount().h> class Room 2 { 3 int width.height. objRoom4. height=r. } void discopyConsCount() { cout<<copyConsCount. copyConsCount++. 15 } 16 void discopyConsCount() { 17 .” for successfully run. 13 height=r. Note that the statement S2 = s1. } Solution: Same as 6.5 of Chapter 5. Include a function that adds two strings to make a third string. Room objroom2(objRoom1). will be perfectly reasonable expression to copy one string to another. 6. (d) Displays a desired string object. Room objRoom3 = objRoom1. objRoom4. (c) Concatenates two strings properly. Room objRoom4. . // string with length 0 And also initialize an object with a string constant at the time of creation like String s2(“Well done!”).18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 cout<<copyConsCount. 6. objRoom4 = objRoom3. Include constructors that will enable us to create an uninitialized string: String s1. (b) Creates objects with string constants. Solution: Study on Constructor and then see solution of chapter 5.dicopyConsCount(). int Room::copyConsCount = 0.1: Design constructors for the classes designed in Programming Exercise 5.1 through 5.3 problem solution. Write a complete program to test your class to see that it does the following tasks: (a) Creates uninitialized string objects. } }. void main() { Room objRooml.2: Define a class String that could work as a user-defined string type. 18 19 string::string(string &amp. 12 } 13 string(char *s). 14 15 void concat(string &amp. 22 strcpy(str. 11 str = new char [length + 1] .m.x) { 20 length = x. 16 17 }.str).Solution: #include 1 2 3 4 #include class string { char *str.str).string &amp. string(string &amp. void display(). 21 str = new char[length + 1].x).n). 5 int length. 6 7 8 public: string() 9 { 10 length = 0. x. 23 .length + strlen(x. m. strcat(str. } 41 42 int main() 43 { 44 string s1.str&lt."\n". 46 47 string s3(" Badly done "). s2.&lt.m.str).concat(s2. strcpy(str.str). . delete str.n.n) 26 27 { length=m. 45 string s2(" Well done ").length+n. 38 39 40 str = new char[length + 1]. 48 s2=s3. 29 30 strcpy(str.length. 28 str=new char[length+1].24 } 25 void string:: concat(string &amp.s3).display().s). 31 } 32 void string:: display() 33 { 34 cout&lt.&lt.string &amp. 35 36 } string::string(char *s) { 37 length = strlen(s). s1. title. Use new operator in constructors to allocate memory space required. If it is. Solution: 1 #include #include 2 #include 3 4 #include #include . 51 52 return 0. If it is not. Design a system using a class called books with suitable member functions and constructors.3: A book shop maintains the inventory of books that are being sold at the shop. 50 s1. publisher and stock position. then the system displays the book details and requests for the number of copies required.display(). The list includes details such as author. If the requested copies are available.49 s2. the sales person inputs the title and author and the system searches the list and displays whether it is available or not. price. otherwise “Required copies not in stock” is displayed. the total cost of the requested copies is displayed. Whenever a customer wants a book. } 53 54 55 56 57 O U T P U T W ell done Badly done W ell done Badly done 6. an appropriate message is displayed.display(). i++) 28 { 29 author[i]=new char[80]. 19 }. int size. . 16 void book_detail(int i).size. float *price. 11 12 int *stock_copy.i&lt.5 6 class book 7 { 8 9 char **author. 13 14 public: 15 book(). 18 int search(). author=new char*[80]. 24 title=new char*[80]. char **title. 10 char **publisher. 20 book :: book() 21 { 22 23 size=4. 26 27 for(int i=0. 17 void buy(int i). 25 publisher=new char*[80]. 75. 42 author[2]="boyelstade". 44 45 stock_copy[0]=200. 52 price[3]=180. 32 33 } stock_copy=new int[size]. price=new float[size]. 48 49 50 price[0]=120. 43 author[3]="shahani". price[1]=115. stock_copy[1]=150.30 title[i]=new char[80]. 34 35 title[0]="object oriented programming with c++". title[2]="electronic circuit theory".5. 53 54 } . 46 stock_copy[2]=50. 36 37 title[1]="programming in ANCI". 39 40 author[0]="balagurusamy". 41 author[1]="balagurusamy". 31 publisher[i]=new char[80]. 47 stock_copy[3]=80.5. 38 title[3]="computer algorithm". 51 price[2]=140. author[i]&lt.setw(15) 60 &lt.setw(16)&lt.&lt. b==0) 79 .&lt. for(int i=0. 67 68 gets(name).&lt.&lt."Title"&lt.b.&lt. 61 62 } 63 int book::search() 64 { 65 char name[80].t[80].setw(12)&lt.i&lt. 77 b=strcmp(t. 72 73 int a. gets(t)." *********book detail **********\n".&lt. 78 if(a==0 &amp. 69 cout&lt. 66 cout&lt.stock_copy[i]&lt.&lt.&lt."Stock copy\n".setw(18)&lt.&lt.title[i]&lt. 59 cout&lt."Author Name" &lt."and title of book in small letter : ".i++) 74 { 75 76 a=strcmp(name.title[i]).&lt. cout&lt."Enter author name : ".author[i])."\n".55 void book::book_detail(int i) 56 { 57 58 cout&lt.&lt.setw(15)&lt.&lt.&lt.&lt.&lt.setw(25)&lt.&amp. 70 71 int count=-1.&lt.size. 0) cout&lt. 104 } .=stock_copy[i]) 97 { 98 remaining_copy=stock_copy[i]-copy.&lt.&lt."Total price = "&lt." This book is not available \n".total_price&lt.&lt." Sorry your required copies is not available \n". } else 103 cout&lt.copy." How many copies of this book is required : ? ". int copy.80 count=i. 81 82 } 83 84 85 return count.&lt. 101 102 cout&lt.&lt. cin&gt. 96 if(copy&lt. } 86 void book::buy(int i) 87 { 88 89 if(i&lt.&lt. 100total_price=price[i]*copy. 94 cout&lt. 90 91 else 92 { 93 book_detail(i). 99 float total_price." TK\n". 95 int remaining_copy.&gt. 112 113 b1. 110 111 result=b1. return 0.search().buy(result).105} 106 107int main() 108 109 { book b1. 114} 115 116 117 118 119 120 121 122 123 124 O U T P U T Enter author name : shahani and title of book in small latter : computer algorithm *********book detail ********* Title computer algorithm Author Name shahani How many copies of thi s book is required : ? 78 Total price = 14079 TK Stock copy 80 . int result. . 10 char **title.6. Use a private member function to implement this. char **publisher.4: Improve the system design in Exercise 6. 9 char **author. Solution: 1 #include #include 2 #include 3 4 #include #include 5 6 class book 7 { 8 static int successful. (c) The number of successful and unsuccessful transactions should be recorded for the purpose of statistical analysis. Use static data members to keep count of transactions.3 to incorporate the following features: (a) The price of the books should be updated as and when required. (b) The stock value of each book should be automatically updated as soon as a transaction is completed. 14 15 16 public: book(). 13 int size.unsuccessful. 11 12 float *price. int *stock_copy. 22 23 }. 19 20 int search(). 29 author=new char*[80]. 41 .i&lt. 30 title=new char*[80].17 void book_detail(int i).size. void showdetail().i++) 33 34 { author[i]=new char[80]. publisher=new char*[80]. 35 title[i]=new char[80]. 21 void edit_price(). 18 void buy(int i). 25 26 book :: book() 27 { 28 size=5. void showtransaction(). 24 int book::unsuccessful=0. 31 32 for(int i=0. int book::successful=0. 36 publisher[i]=new char[80]. 37 } 38 stock_copy=new int[size]. 39 40 price=new float[size]. 61 price[3]=180. 62 price[4]=120. 57 58 price[0]=120. 52 53 stock_copy[0]=200. stock_copy[4]=300. 55 stock_copy[2]=50.5. 48 49 author[1]="balagurusamy".5. 63 64 } 65 66 void book::book_detail(int i) . author[2]="boyelstade". 54 stock_copy[1]=150. 46 47 author[0]="balagurusamy". 59 60 price[1]=115. price[2]=140. 44 45 title[2]="electronic circuit theory".75.42 title[0]="object oriented programming with c++". 51 author[4]="abdus sattar". 56 stock_copy[3]=80. title[4]="complete solution of balagurusamy(c++)". title[3]="computer algorithm". 50 author[3]="shahani". 43 title[1]="programming in ANCI". 69 70 cout&lt.&lt."Enter author name in small letter : ".setw(30)&lt.t[80]."Title"&lt." *********book detail **********\n".title[i]&lt. 79 gets(name). 83 int a.&lt.setw(16)&lt."\n".&lt."Author Name" &lt. 88 b=strcmp(t. cout&lt.&lt.i++) { 86 87 a=strcmp(name.&lt.size.&lt. 81 gets(t).&lt.b. 84 85 for(int i=0."Stock copy\n".stock_copy[i]&lt." title of book in small letter : ".67 { 68 cout&lt.title[i]).&lt. 72 73 } 74 75 int book::search() 76 { 77 char name[80]. 80 cout&lt. 82 int count=-1.author[i]).setw(15) 71 &lt. b==0) 90 91 count=i. .setw(15)&lt.setw(18)&lt.&lt.&lt.author[i]&lt. 89 if(a==0 &amp.&lt.&lt.&lt.&lt.setw(25)&lt.&lt.&amp.&lt. 78 cout&lt.i&lt. 0) 100 101 { cout&lt. 116 } . 114 115 total_price=price[i]*copy. cout&lt.&lt. 96 } 97 98 void book::buy(int i) { 99 if(i&lt."Total price = "&lt. int copy.&lt. 103} 104 105else 106{ 107book_detail(i)." This book is not available \n"." TK\n". 113float total_price.&lt. 108cin&gt.=stock_copy[i]) 111{ 112stock_copy[i]=stock_copy[i]-copy. 102unsuccessful++.92 93 } 94 95 return count. 109 110if(copy&lt. successful++. cout&lt.total_price&lt.copy.&lt." How many copies of this book is required : ? ".&gt.&lt. size.&lt."Enter new price : ".&lt. 128i=search().setw(35)&lt.&lt."Title"&lt.&lt.setw(10)&lt.&lt.&lt.i&lt." To edit price ".117else 118{ 119 120 cout&lt. float p.stock_copy[i] 138 139 &lt.&gt.&lt.&lt.price[i]&lt.p. 127int i.title[i]&lt. } 131 void book::showdetail() 132 { 133 cout&lt.setw(18)&lt.&lt.endl. } 121 } 122 } 123 124 void book::edit_price() 125{ 126cout&lt.&lt." Price per book "&lt. unsuccessful++. 130 price[i]=p.&lt. cin&gt.&lt. 129cout&lt.&lt.&lt." Sorry your required copies is not available \n".i++) { 137 cout&lt.&lt.setw(20) 135 136 &lt.&lt." stock copy 134"&lt. } 140} 141void book::showtransaction() .setw(30)&lt.&lt.setw(22)&lt. for(int i=0.endl. 150int result.endl&lt. cout&lt. } 146 147 int main() 148 149 { book b1.&lt.142{ 143cout&lt.&lt."unsuccessful transaction "&lt.showdetail()."Successful transaction"&lt. 158 b1.successful&lt. 153b1. 154b1."************details after edit price 157 *****************"&lt.showtransaction().&lt.&lt.edit_price().setw(22)&lt. 161} 162 163 164 165 166 .setw(10) &lt.&lt.&lt. 151 152result=b1.setw(34) 144 145 &lt.unsuccessful&lt.&lt.&lt.search().&lt. 156 b1.endl.buy(result).showdetail().endl. 155b1. 159 160 return 0.&lt.&lt.&lt.setw(32)&lt. 5 150 115.5 115.75 electronic circuit theory 50 140 computer algorithm 80 180.167 168 169 170 171 172 173 174 175 O U T P U T Enter author name in small letter : abdus sattar title of book in small letter : complete solution of balagurusamy(c++) *********book detail ********** Title Author Name Stock copy complete solution of balagurusamy(c++) abdus sattar 300 How many copies of this book is required : ? 100 Total price = 12000 TK Title stock copy object oriented programming with c++ 200 programming in ANCI Price per book 120.75 electronic circuit theory 50 140 computer algorithm 80 200 complete solution of balagurusamy(c++) 200 120 .5 complete solution of balagurusamy(c++) 200 Successful transaction 120 unsuccessful transaction 1 0 To edit price Enter author name in small letter : shahani title of book in small letter : computer algorithm Enter new price : 200 ************details after edit price********* ******** Title stock copy object oriented programming with c++ programming in ANCI 200 150 Price per book 120. Syntax of operator function: 1 2 3 4 return type class name : : operator OP (argument list) { function body // task defined } 7. 7. Ans: To define an additional task to an operator.4: How many arguments are required in the definition of an overloaded unary operator? Ans: No arguments are required. is called operator function.2: Why is it necessary to overload an operator? Ans: We can almost create a new language of our own by the creative use of the function and operator overloading techniques.Chapter 7: 7. we must specify what it means in relation to the class to which the operator is applied.5: A class alpha has a constructor as follows: alpha(int a. Can we use this constructor to convert types? . 7. double b).3: What is an operator function? Describe the syntax of an operator function. 7.1: What is operator overloading? Ans: The mechanism of giving special meaning to an operator is known as operator overloading. By which function this is done. In this case friend function allows both approaches. This is referred to conversion function. 7. Therefore it just uses the functionality (functions and data) of the class. So it does not consist the implementation for that class. That’s why it cannot be used to overload the assignment operator. The constructors used for the type conversion take a single argument whose type is to be converted.7: A friend function cannot be used to overload the assignment operator =. 7. Syntax: 1 2 3 4 Operator type name ( ) { (Function Statements) } 7. is valid But A = 2 + B or A = 2 * B will not work. Explain why? Ans: A friend function is a non-member function of the class to which it has been defined as friend. Example: A = B + 2. or A = B * 2. Ans: C++ allows us to define an overloaded casting operator that could be used to convert a class type data to a basic type.8: When is a friend function compulsory? Give an example. Because the left hand operand is responsible for invoking the member function.6: What is a conversion function How is it created Explain its syntax. then we must use friend function. .Ans: No. Ans: When we need to use two different types of operands for a binary operator. (e) The overloaded operator must have at least one operand that is user-defined type. the left operand is implicitly passed to the member function. (h) A constructor can be used to convert a basic type to a class type data. we can change the meaning of an operator. (d) When using an overloaded binary operator. a class type data can be converted to a basic type data.7.9: We have two classes X and Y. (c) Friend functions cannot be used to overload operators. What type of conversion routine should be used and where? Ans: We have to use one class to another class type conversion. Ans: (a) FALSE (b) TRUE (c) FALSE (d) FALSE (e) TRUE (f) FALSE (g) TRUE (h) TRUE 7. 7 } 8 . (b) Operator overloading works when applied to class objects only. (a) Using the operator overloading concept.10: State whether the following statements are TRUE or FALSE.1: Identify the error in the following program. #include <iostream. (g) Through operator overloading. (f)Operator functions never return a value. If a is an object of X and b is an object of Y and we want to say a = b.h> 1 class Space 2 { 3 int mCount. 7. The type-conversion function to be located in the source class or in the destination class. public: 4 Space() 5 { 6 mCount = 0. 19 else if(w1==mSunday && w2==mSunday) 20 return 1. WeekDays& w2) 11 { if(w1== mSunday && w2==mSunday) 12 return 1. 21 else if(w1==mSunday && w2==mSunday) 22 return 1. } }. 10 bool op==(WeekDays& w1. } Solution: The argument of Space() function is void type. Here return space (mCount). void main() { Space objSpace.2: Identify the error in the following program. 14 else if(w1==mSunday && w2==mSunday) 15 return 1. But ‘mCount’ argument is sending to Space() function through return space(mCount). 16 else if(w1==mSunday && w2==mSunday) 17 return 1. 7. 18 else if(w1==mSunday && w2==mSunday) return 1. 23 else . objSpace++. Statement. so when this function is called there are no argument can send to it.h> 1 enum WeekDays 2 { 3 mSunday' 4 mMonday. 5 mWednesday. 6 mThursday. 13 else if(w1==mSunday && w2==mSunday) return 1.9 10 11 12 13 14 15 16 17 18 19 20 21 Space operator ++() { mCount++. 8 mSaturday 9 }. #include <iostream. return Space(mCount). 7 mFriday. mtuesday. replaced by return space(). void main() . 1 #include <iostream. All other code will remain same. } }. float h) 9 :mWidth(w). else cout<<"Different day". w2 = mSunday. if(w1==w2) cout<<"Same day". 5 public: 6 Room() { 7 } 8 Room(float w.24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 return 0. } Solution: bool OP = = (WeekDays & w1.h> class Room 2 { 3 float mWidth. 7.3: Identify the error in the following program. 14 } 15 16 17 18 19 20 21 22 23 24 float getWidth() { } float getLength() { return mLength. 4 float mLength. mLength(h) 10 { 11 } operator float () 12 { 13 return (float)mWidth * mLength. } void main() { WeekDays w1 = mSunday. WeekDays & w2) replaced by bool operator = = (Weekdays & w1. WeekDays & w2 ). } 9 FLOAT operator+(FLOAT f1). Overload all the four arithmetic operators so that they operate on the objects of FLOAT.1: Crate a class FLOAT that contains one float data member. 7.5.25 26 27 28 29 30 31 32 33 34 { Room objRoom1(2. 2.h> 1 2 3 4 class FLOAT { float data. So it should write as follows.5) float fTotalArea. but there is no return statement in getWidth() function. cout<< fTotalArea. fTotalArea = objRoom1. } Solution: The float getWidth() function return float type data. . 1 2 3 4 float getWidth() { return mWidth. 5 public: 6 7 FLOAT(){}. } All other code will remain unchanged. Solution: #include<iostream. FLOAT(float d) 8 { data=d. 18 return (temp). 28 temp.data=data+f1. 23 return temp. 34 return (temp). 19 } 20 FLOAT FLOAT::operator-(FLOAT f2) 21 { FLOAT temp. 33 temp.data.data=data/f4. . 24 25 26 } FLOAT FLOAT::operator*(FLOAT f3) { 27 FLOAT temp. 13 }.data. return temp.data=data*f3. 11 FLOAT operator*(FLOAT f3).data=data-f2. 17 temp.10 FLOAT operator-(FLOAT f2). 22 temp. 29 30 31 32 } FLOAT FLOAT::operator/(FLOAT f4) { FLOAT temp. FLOAT operator/(FLOAT f4). 12 void display(). 14 FLOAT FLOAT::operator+(FLOAT f1) 15 { 16 FLOAT temp.data.data. display(). 51 cout<<" F1+F2 = ". 50 F2.1).display(). 54 F4. F5=F1*F2.F2.F6.5). 43 F2=FLOAT(3.display(). 57 F6.F4. 56 cout<<" F1/F2= ". 48 F1.display(). 53 cout<<" F1-F2 = ". 45 F4=F1-F2. 49 cout<<" F2 = ".display(). 58 return 0. 59 } . 42 F1=FLOAT(2. 55 cout<<" F1*F2 = ".F5. F5.display(). 47 cout<<" F1 = ".F3. 46 F6=F1/F2.35 } 36 void FLOAT:: display() 37 { cout<<data<<"\n". 44 F3=F1+F2. 38 } 39 int main() 40 { 41 FLOAT F1. 52 F3. Note that we cannot add polar values of two points directly.60 61 62 63 64 65 66 O U T P U T F1 = 2. This requires first the conversion of points into rectangular coordinates.75 F1/F2= 0.1 F1+F2 = 5.806452 7. then adding the respective rectangular coordinates and finally converting the result back into polar coordinates.2: Design a class Polar which describes a point in the plane using polar coordinates radius and angle.5 F2 = 3. You need to use the following trigonometric formula: .6 F1-F2 = -0.3 Use the overload + operator to add two objects of Polar.6 F1*F2 = 7. A point in polar coordinates is shown below figure 7. x = r * cos(a).float a1) .1416 4 5 class polar { float r.x. Solution: 1 #include<iostream. 8 polar(float r1. 11 }.y. 6 public: 7 polar(){}.h> 2 #include<math. 10 void display(void).h> 3 #define pi 3.float a1). 9 polar operator+(polar r1). 12 13 polar :: polar(float r1. y = r * sin(a).a. a = atan(y/x). //arc tangent r = sqrt(x*x + y*y). x+R.p2.x.y/R.x=x+r1. 18 } 19 20 21 polar polar :: operator+(polar r1) { 22 polar R.a=atan(R.p3.y=y+r1.14 { r=r1.x).x*R. } 35 36 int main() 37 { 38 polar p1.y.y). 23 24 R. 26 R. R. 25 R.y*R.r=sqrt(R. . 17 y=r*sin(a). 16 x=r*cos(a). 29 } 30 31 void polar::display() 32 { 33 34 cout<<"radius = "<<r<<"\n angle = "<<a*(180/pi)<<"\n". 27 28 return R. 15 a=a1*(pi/180). 999998 P2 : radius = 8 angle = 44. 48 cout<<" p3 : \n ". Define all possible matrix operations for MAT . 49 p3. 42 p2=polar(8.a).display(). 44 cout<<" p1 : \n". 50 51 } 52 53 54 55 O U T P U T Enter radius and angle : 10 45 P1: radius = 10 angle = 44.39 float r. 40 cout<<" Enter radius and angle : ".display(). cin>>r>>a.999998 P3 : radius = 18 angle = 44.45).a. 43 p3=p1+p2.display(). 47 p2. 46 cout<<" p2 : \n ". return 0.999998 7.3: Create a class MAT of size m * n. 41 p1=polar(r. 45 p1. mat operator*(mat m2).type objects.i<r.mat &). 10 friend istream & operator >>(istream &.h> 3 4 5 class mat { float **m.mat &). Solution: 1 #include<iostream. 21 for(int i=0. 19 cs=c.i++) 22 23 m[i]=new float1. 13 mat operator-(mat m2). 16 void mat::creat(int r.int c). 7 public: 8 mat(){} 9 void creat(int r.int c) 17 { 18 rs=r.h> 2 #include<iomanip.cs. 12 mat operator+(mat m2). 6 int rs. 20 m=new float *[r]. } . 14 15 }. 11 friend ostream & operator <<(ostream &. i++) { for(int j=0.j++) 32 { 33 din>>a. 48 } .j++) 44 { 45 dout<<setw(5)<<a. 36 37 } ostream & operator<<(ostream &dout. 29 for(int i=0.mat &a) 38 { 39 40 41 int r.c. 27 r=a.i<r.j<c. r=a. } 34 } 35 return (din).m[i][j].rs.c. 46 } 47 dout<<"\n". 42 43 for(int i=0.i++) 30 { 31 for(int j=0.m[i][j]. mat &a) int r. 28 c=a.cs. c=a.j<c.i<r.cs.rs.24 25 istream & 26 { operator>>(istream &din. i<rs. 58 } 59 } 60 return mt.i<rs.j++) 69 { 70 mt.j<cs.cs). 71 } 72 } 73 return mt.j++) 57 { mt.i++) 55 { 56 for(int j=0.creat(rs.j<cs.creat(rs.m[i][j]=m[i][j]+m2. .m[i][j].return (dout). for(int i=0. 53 mt. mt. 61 } 62 63 mat mat::operator-(mat m2) 64 65 66 67 68 { mat mt. 54 for(int i=0.m[i][j]=m[i][j]-m2.i++) { for(int j=0.m[i][j]. 49 50 51 52 } mat mat::operator+(mat m2) { mat mt.cs). k<m2.m[k][j].rs.creat(r1.m4. . 95 cout<<" Enter first matrix size : ".m[i][j]+=m[i][k]*m2.creat(rs.cs. 96 cin>>r1>>c1.cs).m3. } 87 } 88 89 return mt.i++) 81 { 82 for(int j=0.j<m2.m[i][j]=0. 94 int r1.r2.j++) 83 { 84 mt. 79 80 for(int i=0.m5.c1.c2. 98 cout<<"m1 = ".m2. 85 for(int k=0.c1). 78 mt.74 } 75 76 77 mat mat::operator*(mat m2) { mat mt. 97 m1.k++) 86 mt.m2.i<rs. 90 } 91 92 int main() { 93 mat m1. 112 cout<<" m1 + m2: "<<endl.creat(r2. 117 cout<<" m1 . 115 116 m4=m1-m2.m2:"<<endl.c2). 102 cout<<"m2 = ". 100 cout<<" Enter second matrix size : ". 119 } 120 121 122 123 else cout<<" Summation & substraction are not possible n"<<endl <<"Two matrices must be same size for summation & "<<endl<<endl. cin>>r2>>c2. 103 cin>>m2. 107 cout<<m2. if(r1==r2 && c1==c2) 109 { 110 m3.c1).creat(r1. substraction . 118 cout<<m4<<endl<<endl. 101 m2. 105 cout<<m1. 108 cout<<endl<<endl. 104 cout<<" m1:"<<endl.creat(r1.c1). 114 m4. 111 m3=m1+m2. 106 cout<<" m2: "<<endl.99 cin>>m1. 113 cout<<m3<<endl. 124 if(c1==r2) 125 { m5=m1*m2. 126 cout<<" m1 x m2: "<<endl. 132 return 0. 127 cout<<m5. } 133 134 135 136 137 138 139 140 141 142 143 144 145 146 O U T P U T Enter first matrix size : 2 2 m1 = 1 2 . 128 } 129 else 130 cout<<" Multiplication is not possible "<<endl 131 <<" column of first matrix must be equal to the row of second matrix ". h> #include<stdio. Solution: #include<iostream. public: void input(){gets(str).4: Define a class String.3 4 Enter second matrix size : 2 2 m2 = 5 6 7 8 m1 = 1 2 3 4 m2 = 5 6 7 8 m1+m2: 6 8 10 12 m1-m2: -4 -4 -4 -4 m1 x m2: 19 43 22 50 7.} int operator==(string s2).h> 4 class string 5 { 6 7 8 9 char str[1000]. Use overload == operator to compare two strings.h> 1 2 3 #include<string. . 13 if(t==0) 14 t=1. 33 34 } .str). 15 else 16 t=0.st2[1000].input(). 24 cout<<" Enter 1st string : ". 23 string s1. 28 29 if(s1==s2) 30 cout<<" Two strings are equal ". 11 int string::operator==(string s2) 12 { int t= strcmp(str. 25 s1. 27 s2.10 }.s2. 17 18 return t. return 0. } 19 20 int main() 21 { 22 char st1[1000].input(). 26 cout<<" enter 2nd string : ". 31 else 32 cout<<" Two string are not equal ".s2. 35 36 37 O U T P U T Enter 1st string : our sweetest songs tel our saddest thought enter 2nd string : a burning desire lead to success.5: Define two classes Polar and Rectangle to represent points in the polar and rectangle systems.y. Use conversion routines to convert from one system to the other.h> 2 #include<math. void conversion_point::set_xy() 13 14 15 { cout<<"Enter the value of x & y : ".h> 3 #define pi 3. 8 void set_r_theta(). 11 12 void conversion(int t). }. 9 void show_xy(). Two string are not equal 7. 6 public: 7 void set_xy().theta. . Solution: 1 #include<iostream.1416 4 class conversion_point 5 { float x.r. 10 void show_r_theta(). 16 17 } void conversion_point::set_r_theta() 18 19 { cout<<"Enter the value of r & theta :". } 35 36 void conversion_point::conversion(int t) 37 { 38 39 40 if(t==1) { r=sqrt(x*x+y*y). . } 23 24 25 void conversion_point::show_xy() { cout<<" CERTECIAN FORM :\n" 26 <<" x = "<<x<<"\n" 27 <<" y = "<<y<<"\n". 21 22 theta=(pi/180)*theta.cin>>x>>y. 28 29 } void conversion_point::show_r_theta() 30 { 31 cout<<" POLAR FORM :\n" 32 <<" r = "<<r<<"\n" 33 34 <<" theta = "<<(180/pi)*theta<<" degree \n". 20 cin>>r>>theta. 41 if(x!=0) 42 { 43 theta=atan(y/x). 44 show_r_theta(). 59 60 } } 61 62 int main() 63 { 64 65 conversion_point santo. int test. } 52 53 } 54 else if(t==2) 55 { 56 x=r*cos(theta). . 58 show_xy(). 57 y=r*sin(theta). 45 } 46 47 else 48 { 49 cout<<" POLAR FORM :\n" 50 <<" r = "<<r<<"\n" 51 <<" theta = 90 degree\n". 340073 degree . 69 if(test==1) 70 santo. 73 santo.set_r_theta(). 74 75 76 return 0.conversion(test).cout<<" press 1 to input certecian point \n" 66 <<" press 2 to input polar point \n " 67 <<" what is your input ? : ".403124 theta = 51. 71 else if(test==2) 72 santo. } 77 78 79 80 81 82 O U T P U T Press 1 to input certecian point Press 2 to input polar point what is your input ? 1 Enter the value of x & y : 4 5 POLAR FORM : r = 6.set_xy(). 68 cin>>test. Single inheritence : Only one derived class inherited from only one base class is called single inheritence. This is known as multiple inheritence.Multiple inheritence : A class can inherit the attributes of two or more classes. visibility. 2.1: What does inheritance mean in C++? Ans:The mechanism of deriving a new class from an old one is called inheritance. Ans:Different forms of inheritence: 1. Example: Let A is a base class and B is a new class derived from A This is written in program as following: class A {………. class B : Public A {……. visibility B3 1 { (Body of D) 2 3 } ..Chapter 8: 8. The old class is referred to as the base class and the new one is called derived class.2: What are the different forms of inheritance? Give an example for each. Example : Class D : visibilityB1.}. 8.B2.}. Hybrid inheritance: When multi level and multiple inheritances are applied to an inheritance. and another class is derived from this derived class and so on... Class B : Public A { ….* visibility may be public or private. // base class. }. 3. Class ECE : Public Engineering { …… }. * here all inheritance are considered as public you can private inheritance also. 4. then it is called hierarchical inheritance. . Class Engineering : Public student { ……}.}. }. Class Arts : Public student { ……}. then it is called multilevel inheritance.. as you wish. Class C : Private B{ …. }. }. 5. then it is called Hybrid inheritance. Example : This design is implemented in program as follows: Class student { …… }. Class EEE : Public Engineering { …… }.Hierarchical inheritance: It the inheritance follows the hierarchical design of a program.Multilevel inheritance : It a class is derived from a base class. Class Medical : Public student {……. Example : Class A { …. Class CSE : Public Engineering { ……. 4 public: int get_a().h> 1 class B 2 { 3 int a. 3 * visibility mode may be public or private.3: Describe the syntax of the single inheritance in C++. how? Remember.Example : In program : Class student {……}.4: We know that a private member of a base class is not inheritable. the base class cannot be modified. 7 class D:public B 8 { .}. or protected 8. 8. The following example explains this : #include<iostream. 6 }. Ans:Syntax of single inheritance: Class Derived name : visibility mode Base_class name 1 { Body of derived class 2 }. 5 void set_a(). Class test : public student {……}. Is it anyway possible for the objects of a derived class to access the private members of the base class? If yes. // a is private that can not be inherited. Class result : public test {……. Class result : public sports {…….}. Ans:Yes. It is possible for the objects of derived class to access the private member of the base class by a member function of base class which is public. display_a(). void D :: display_a() { cout<<" a = "<<get_a()<<"\n". } int B :: get_a() { return a. (b) Private member of B can not be inherited in D2 Protected member of B remains protected in D2 Public member of B remains public in D2 8. } void main() { D d. d.).set_a(). Ans:(a) Private member of B can not be inherited in D1 Protected member of B become private in D1 public member of B become private in D1. } 8. // a is accessed by member function get_a(). }. } void B :: set_a() { a=156271.). d.5: How do the properties of the following two derived classes differ? (a) class D1: private B(// ….6: When do we use the protected visibility specifier to a class member? . (b) class D2: public B(//….9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 int b. public: void display_a(). Visibility B2.10: When do we make a class virtual? Ans:To avoid the duplication of inherited members due to multiple paths between base and derived classes we make base class virtual. public B(//….). 8. then we use visibility modifier protected... ..7: Describe the syntax of multiple inheritance. 8. (b) class A: public C. .11: What is an abstract class? . 8.Ans:When we want access a data member by the member function within its class and by the member functions immediately derived from it. 8. 8.9: WWhat is a virtual base class? Ans:Whey multiple paths between a bass class and a derived class are exist then this base class is virtual base class..). A base class can be made as virtual just adding ‘virtual’ keyword before this base class. When do we use such an inheritance? Ans: Syntax : 1 Class D : Visibility B1. 2 { (Body of D) 3 } 4 Then we want of combine several feature to a single class then we use multiple inheritance.8: What are the implications of the following two definitions? (a) class A: public B. .. Ans:Two are same.. public C(//…. 15: Describe how an object of a class that contains objects of other classes created? Ans:By inheriting an object can be created that contains the objects of other class. The class which contains the object cannot access any protected or private members of the contained class(unless the container it was made a friend in the definition of the contained class). Example : 1 class A .Ans:An abstract class is one that is not used to create objects. The class D does not contain any data members of its own. because the derived is-a” base class.12: In what order are the class constructors called when a derived class object is created? Ans:According to the order of derived class header lines 8. That is. 8. The derived class can be safely down cast to the base class. Difference : In inheritance the derived class inherits the member data and functions from the base class and can manipulate base public/protected member data as its own data. 8. why? Ans:D does not require any construct or because a default constructor is always set to class by default. Container : a class contains another object as member data. By default a program which constructs a derived class can directly access the public members of the base class as well. the HAS-A relationship where A has-a member that is an object of class B.13: Class D is derived from class B. Does the class D require constructors? If yes.14: What is containership? How does it differ from inheritance? Ans:Containership is another word for composition.The relationship between the container and the contained object is “has-a” instead of “is-a” 8. (b) Inheritance aids data hiding. (h) We can prevent the inheritance of all members of the base class by making base class virtual in the definition of the derived class. int b. (e) Defining a derived class requires some changes in the base class.1: Identify the error in the following program. }. public: void dosomething(). if object of B is created . public: void donothing(). . }.2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 { int a. 3. 2. 8. Ans: (a) TRUE (b) FALSE (c) TRUE (d) TRUE (e) FALSE (f) TRUE (g) TRUE (h) FALSE 8. class B: class A { int b. Now 1. (c) One of the advantages of inheritance is that it provides a conceptual framework. (d) Inheritance facilitates the creation of class libraries. void donothing ( ). then if contains: void dosomething ( ). (g) It is legal to have an object of one class as a member of another class.16: State whether the following statements are TRUE or FALSE: (a) Inheritance helps in making a general class into a more specific class. (f) A base class is never used to create objects. public: AnualTest(int m1. class Student { char* name.2: Identify the error in the following program. int m2) :mark1(m1). . public: Student() { name = "AlanKay". } }.h>. } void setNumber(int no) { rollNumber = no. rollNumber = 1025. mark2.h>.. } }. } Solution: Constructor and Private (data & function) can not be inherited. int rollNumber. mark2(m2) { } int getRollNumber() { return Student::getRollNumber(). cout<< test1. 1 class A 2 { 3 public: 4 A() 5 { 6 7 cout<< "A". } int getRollNumber() { return rollNumber. 8. class AnualTest: Student { int mark1. void main() { AnualTest test1(92 85). #include <iostream.getRollNumber().1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 #include <iostream. } }. void main() { F f. class D { public: D() { cout << "D". } . virtual E { public: F() { cout<< "F". class B: public A { public: B() { cout<< "B". class F: B. public D { public: E() { cout<< "D". } }. } }. } }. } }. class C: public B { public: C() { cout << "C". class E: public C.8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 } }. }. void main() { ABAC abac. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 #include <iostream. but not E. ABAC { int k. 8. }. class ABAC: AB. class AC: A. AC { int l. }.3: Identify the error in the following program. } .h>. }. class AB: virtual A { int j.54 55 Solution: The inheritance can be represented as follows : Here B is virtual. cout << "sizeof ABAC:" << sizeof(abac). class A { int i. y3. State reasons. } }. If we write class ABAC. class Z: X { public: void f() { int z1.z2. after #include it will not show any error massage.h> 2 class X 3 { 4 private: int x1. 5 Protected: 6 int x2. y3 = x3. 7 public: 8 int x3. 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 class Y: public X { public: void f() { int y1. z2 = x2.y2.z3. // Program test 1 #include <iostream. y1 = x1. } }. . z3 = x3. 9 }. z1 = x1. y2 = x2. 8. Here there is no identification of ABAC.4: Find errors in the following program.Solution: The inheritance can be represented as follows: Class AC: A. n = z.x2. m = y.5: Debug the following program.n. Z z.29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 main() { int m. is not valid 8. x1. } Solution: Here x1 is private. } }. public: void display().x3. Y y. { cout << b2 <<"\n". is not valid m = z.x1. // Test program 1 #include <iostream. y1 = x1.x2. . p = z. m = z. 4 public: 5 void display(). 6 { 7 cout << b1 <<"\n". n = y.x1.h> 2 class B1 3 { int b1. p = y.p. 9 10 11 12 13 14 15 16 17 class B2 { int b2. is not valid m = y. so x1 cannot be inherited. is not valid z1 = x1. x1.x3. 8 } }. (c) Compute and deposit interest. Current account holders should also maintain a minimum balance and if the balance falls below this level a service charge is imposed. Use member functions to initialize class members.B2::display(). necessary and update the balance. account number and type of account. Create a class account that stores customer name. The current account provides cheque book facility but no interest. From this derive the classes cur_acct and sav_acct to make them more specific to their requirements. Here display() function should be declared as virtual in B1 class. (b) Display the balance. Do not use any constructors. 8. impose penalty.h> . public B2 { //nothing here }.display ( ).display() d. show ‘ambiguity error’. d. Include necessary member functions in order to achieve the following tasks: (a) Accept the deposit from a customer and update the balance. Solution: #include<iostream.B1::display().18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 class D: public B1. } Solution: d. main() { D d. (d) Permit withdrawal and update the balance. one called as savings and the other as current account. d. The savings account provides compound interest and withdrawal facilities but no cheque book facility.h> 1 #include<stdio. (e) Check for the minimum balance.1: Assume that a bank maintains two kinds of accounts for customers. 15 6 7 class account 8 { 9 protected: 10 char name[100].h> 4 5 #define minimum 500 #define service_charge 100 #define r 0. 24 } 25 class cur_acct: public account 26 { . 14 15 }. 16 void account::creat(char *t) 17 { 18 19 cout<<" Enter customer name :".t). 20 gets(name). char ac_type[100]. 11 int ac_number. 12 public: 13 void creat( char *t). 23 cin>>ac_number.2 #include<string. 22 cout<<" Enter account number :". 21 strcpy(ac_type.h> 3 #include<math. } . 48 if(test==0) 49 50 51 balance+=w. 28 public: 29 void deposite(float d). void cur_acct::deposite(float d) 34 { 35 balance=d. 30 void withdraw(float w). 36 } 37 38 void cur_acct::withdraw(float w) 39 { if(balance<w) 40 cout<<" sorry your balance is less than your withdrawal amount \n". 31 void display(). 32 33 }. 41 else 42 { 43 balance-=w. 47 cin>>test.private: 27 float balance. 44 45 46 if(balance<minimum) cout<<"\n your current balance is :"<<balance<<" which is less than"<<minimum<<"\n y to avoid discharge \n "<<" Do you want to withdraw ? press 1 for yes press 0 for no \n"< int test. year) : ". 64 void set_date(int a. 56 } 57 class sav_acct:public account 58 { 59 float balance.} 65 void interest().52 } 53 54 void cur_acct::display() 55 { cout<<"\n Now balance = "<<balance<<"\n".y.e day.y. 63 void withdraw(float w).y. 73 set_date(x. 72 cin>>x>>y>>z. 66 }. 74 balance=d. 60 int d. void display(). 61 public: 62 void deposite(float d).y=c.z. 71 cout<<" Enter today's date(i.month.int c){d=a.z).m=b.m. 75 76 } .int b. 67 68 69 void sav_acct::deposite(float d) { 70 int x. 31. 90 if(test==0) 91 balance+=w.31.30.31}. 83 84 if(balance<minimum) 85 86 { cout<<"\n your current balance is :"<<balance<<" which is less than"<<minimum<<"\n yo to avoid discharge \n "<<" Do you want to withdraw ? press 1 for yes press 0 for no \n"< 87 88 int test.31.30. 89 cin>>test.30. 92 } 93 } 94 95 } 96 void sav_acct::display() 97 { cout<<"\n Now balance = "<<balance. 98 } 99 void sav_acct::interest() 100 101 { int D[12]={31. 80 else 81 { 82 balance-=w.void sav_acct::withdraw(float w) 77 78 { if(balance<w) 79 cout<<" sorry your balance is less than your withdrawal amount \n".30.28. .31.31. 115 tday=fday-iday. 107 for(int i=0.i++) 112 { iday+=D[i].year) ".i++) 108 { 109 fday+=D[i].fday. 116 float ty.i<m1.102 int d1. 123} 124 125 126 int main() { . 118 float intrst. 106 fday=d1. 105 iday=d.month. 103 cout<<" Enter today's date :(i.i<m. 119 120 intrst=ty*r*balance.e day. 122 balance+=intrst. 121 cout<<" Interest is : "<<intrst<<"\n". 117 ty=float(tday)/365+y1-y. 113 } 114 int tday.y1. cin>>d1>>m1>>y1. 110 } 111 for(i=0.m1. 104 int iday. 127 sav_acct santo. int t. 138 139 140 if(t==1) santo. cout<<" Enter your deposit amount : ".display(). 131 santo. return 0.creat("savings"). float w. . cout<<"\n press 1 to see your interest : \n" 135 <<" press 0 to skip : ". cin>>d. 129 130 float d. 144 145 146 147} 148 149 150 151 santo.display(). santo.deposite(d).interest(). 143 cin>>w.withdraw(w). 128 santo. 141 142 cout<<"\n Enter your withdrawal amount :". 132 133 134 santo. 136 137 cin>>t. h> #define minimum 500 .h> #include<stdio.h> 2 #include<string.616211 8.61644 Enter your withdrawal amount :500 Now balance = 9635.2: Modify the program of exercise 8.e day.h> 3 4 #include<math.year) : 13 7 2010 8 2010 Now balance = 10000 press 1 to see your interest : press 0 to skip : 1 Enter today’s date :(i. Solution: 1 #include<iostream.month. year) 15 Interest is : 135.1 to include constructors for all three classes.month.e day.152 153 154 155 156 157 158 159 160 O U T P U T Enter customer name :Rimo Enter account number :10617 Enter your deposit amount : 10000 Enter today’s date(i. n). 13 public: 14 account( char *n.char *t. 15 }.5 #define service_charge 100 6 #define r 0. void deposit(float d){balance=d.} . 19 ac_number=no. public: void withdraw(float ww).t).d. 12 char ac_type[100]. 18 strcpy(ac_type.int no) 16 17 { strcpy(name.w.char *t.int no). 11 int ac_number.15 7 8 9 class account { protected: 10 char name[100]. 20 21 } 22 23 class cur_acct: public account 24 { 25 26 27 28 29 private: float balance. account::account(char *n. 35 withdraw(w). 40 41 void cur_acct::withdraw(float ww) 42 { 43 44 45 46 if(balance<ww) cout<<" sorry your balance is less than your withdrawal amount \n".char *t. 53 if(test==0) 54 balance+=w. 48 49 50 51 52 if(balance<minimum) { cout<<"\n your current balance is :"<<balance<<" which is less than"<<minimum<<"\n your avoid discharge \n "<<" Do you want to withdraw ? press 1 for yes press 0 for no \n"<<" int test. 34 deposit(d).float dp. 36 37 } 38 void display(). 39 }.t.number) { 32 d=dp. else { 47 balance-=ww. .30 cur_acct(char *n.int number. 33 w=wd. cin>>test.float wd): 31 account(n. 77 78 79 w=wd. public: void deposite(float d){balance=d.int number.number) { float d. 70 71 void display().y=2010.t.m=1.m.} 55 else 56 .set_date(). 73 sav_acct(char *n. d=dp. 57 } 58 } 59 60 void cur_acct::display() 61 { 62 cout<<"\n Now balance = "<<balance<<"\n". void set_date(){d=12.w. .float dp.} 69 void withdraw(float w).y. 63 } 64 class sav_acct:public account 65 { 66 67 68 float balance.float wd): 74 75 76 account(n.} 72 void interest(). int d. deposite(d).char *t. } 98 else 99 .interest(). 80 withdraw(w). 88 else 89 { 90 balance-=w. 96 if(test==0) 97 balance+=w. 81 82 } 83 84 }. 95 cin>>test. void sav_acct::withdraw(float w) 85 { 86 if(balance<w) 87 cout<<" sorry your balance is less than your withdrawal amount \n". 91 if(balance<minimum) { 92 cout<<"\n your current balance is :"<<balance<<" which is less than"<<minimum<<"\n your 93 avoid discharge \n "<<" Do you want to withdraw ? press 1 for yes press 0 for no \n"<<" 94 int test. 100 } 101 102 103 } void sav_acct::display() 104{ . fday.28.month.m1.e day. 109 int d1.year) ".31. 112 int iday. 110 cout<<" Enter today's date :(i. balance=balance*pow((1+r).30. 126 127 } 128 int main() 129 { .31. 114 fday=d1.31.i++) 119 { 120 iday+=D[i].i<m. 121 } 122 int tday. 117 } 118 for(i=0.30.31. 111 cin>>d1>>m1>>y1. 123 tday=fday-iday. 113 iday=d.30.y1.ty). 124 float ty.cout<<"\n Now balance = "<<balance. 115 for(int i=0.30.i++) { 116 fday+=D[i]. 105 106} 107 108 void sav_acct::interest() { int D[12]={31.31}.31. 125 ty=float(tday)/365+y1-y.i<m1. number. 137 cout<<" Enter your deposit amount : ".display(). } . 144 sav_acct c("savings". 139 140 cout<<" Enter your withdrawal amount :". 146 147 148 149 150 151 152 153 154 return 0. 136 cin>>number.d.130 float d. 145 c.display(). 138 cin>>d. 143 //s.name.d.number. 142 cin>>w. 134 cout<<" Enter account number :".w).w). 133 gets(name). 135 int number. 141 float w. //cur_acct s("current". 132 char name[100]. 131 cout<<" Enter customer name :".name. Specify all classes and define functions to create the database and retrieve individual information as and when required. The figure also shows the minimum information required for each class.3: An educational institution wishes to maintain a database of its employees.year) 13 7 2010 Now balance = 4160. The database is divided into a number of classes whose hierarchical relationships are shown in following figure. .month.155 156 157 158 159 160 161 O U T P U T Enter customer name :mehedi Enter account number :1457 Enter your deposit amount : 5000 Enter your withdrawal amount :1200 Enter today’s date :(i.875977 8.e day. h> #include<string. 8 char name[100].h> 4 class staff 5 { 6 7 public: int code. 9 public: .h> 2 3 #include<iomanip.Solution: 1 #include<iostream. char *p) { 22 strcpy(sub.p). 13 } 14 }.void set_info(char *n. 15 16 17 class teacher : public staff { 18 19 protected: char sub[100]. 20 public: 21 void set_details(char *s. 12 code=c.publication[100]. 28 } 29 }. 23 } 24 void show() 25 { 26 cout<<"name"<<setw(8)<<"code"<<setw(15)<<"su 27 <<"publication"<<endl<<name<<setw(8)<<code<<setw(25)<<sub<<setw(22)<<publication<<endl.n). 30 31 class officer:public staff 32 { 33 34 char grade[100].s).int c) 10 { 11 strcpy(name. public: .strcpy(publication. void set_details(char *g) 35 { 36 strcpy(grade. } 44 }.g). 37 } 38 39 void show() 40 { 41 cout<<" name "<<setw(15)<<"code"<<setw(15)<<"Category "<<endl 42 43 <<name<<setw(10)<<code<<setw(15)<<grade<<endl. public: void set_wage(float w){wage=w. 45 class typist: public staff 46 { 47 48 protected: float speed. public: 49 void set_speed(float s) 50 { 51 speed=s. 54 class regular:public typist 55 { 56 57 58 protected: float wage.} 59 void show() . 52 } 53 }. " Tata McGraw Hill").420). t. .{ 60 cout<<"name"<<setw(16)<<"code"<<setw(15)<<"speed"<<setw(15) 61 62 63 <<"wage"<<endl<<name<<setw(10)<<code<<setw(15)<<speed <<setw(15)<<wage<<endl. t.set_info("Ataur". 65 66 class causal:public typist { 67 float wage. 74 } 75 76 }.} 70 void show() { 71 cout<<"name"<<setw(16)<<"code"<<setw(15)<<"speed"<<setw(15) 72 <<"wage"<<endl<<name<<setw(10)<<code<<setw(15)<<speed 73 <<setw(15)<<wage<<endl. 68 public: 69 void set_wage(float w){wage=w. 77 78 int main() 79 { 80 81 82 83 84 teacher t. } 64 }.set_details("programming with c++". 333).333).5). cout<<" About causal typist :"<<endl. . o.show(). 104 105 106} 107 108 109 return 0. 87 o. 94 ct. 95 ct.show(). 91 rt. 92 93 causal ct.set_wage(15000). 97 98 99 cout<<" About teacher: "<<endl.set_speed(78. cout<<" About officer:"<<endl. 86 o.show().set_wage(10000). 89 rt.show(). 90 rt. Rashed".set_details("First class").set_info("Kawser Ahmed".9).set_info("Md.85 officer o. 100 cout<<" About regular typist :"<<endl.222). 101 102 103 rt. 96 ct. t. ct. 88 regular rt.set_info("Robiul Awal".set_speed(85. 110 111 112 113 114 115 116 O U T P U T About teacher: name code Ataur 420 subject publication programming with c++ Tata McGraw Hill About officer: name Md. Rashed code Category 222 First class About regular typist : name Robiul Awal code 333 speed 85.5 wage 15000 About causal typist : name Kawser Ahmed code 333 speed 78.900002 wage 10000 8.4: The database created in exercise 8.3 does not include educational information of the staff. It has been decided to add this information to teachers and officers (and not for typists) which will help management in decision making with regard to training, promotions etc. Add another data class called education that holds two pieces of educational information namely highest qualification in general education and highest professional qualification. This class should be inherited by the classes teacher and officer. Modify the program of exercise 8.19 to incorporate these additions. Solution: 1 #include<iostream.h> 2 #include<iomanip.h> 3 #include<string.h> 4 5 6 class staff { protected: 7 int code; 8 char name[100]; 9 public: 10 void set_info(char *n,int c) 11 { 12 strcpy(name,n); code=c; 13 } 14 15 }; 16 class education:public staff { 17 protected: 18 19 20 char quali[100]; public: void set_qualification(char *q){strcpy(quali,q);} 21 }; 22 23 class teacher : public education 24 { 25 26 27 protected: char sub[100],publication[100]; public: void set_details(char *s,char *p) 28 { 29 strcpy(sub,s);strcpy(publication,p); 30 } 31 void show() 32 { 33 cout<<" name "<<setw(8)<<"code"<<setw(15) 34 <<"subject"<<setw(22)<<"publication" 35 <<setw(25)<<"qualification"<<endl 36 <<name<<setw(8)<<code<<setw(25) <<sub<<setw(18)<<publication<<setw(25)<<quali<<endl; 37 } 38 39 }; 40 class officer:public education 41 { 42 char grade[100]; 43 44 45 public: void set_details(char *g) { 46 strcpy(grade,g); 47 48 } 49 50 void show() 51 { 52 cout<<" name "<<setw(15)<<"code"<<setw(15)<<"Catagory " <<setw(22)<<"Qualification"<<endl<<name<<setw(10) 53 <<code<<setw(15)<<grade<<setw(25)<<quali<<endl<<endl; 54 } 55 56 }; 57 class typist: public staff 58 { 59 protected: 60 float speed; 61 public: 62 void set_speed(float s) { 63 speed=s; 64 } 65 66 }; class regular:public typist 67 { 68 protected: 69 float wage; 70 public: 71 void set_wage(float w){wage=w;} 72 void show() 73 { cout<<" name "<<setw(16)<<"code"<<setw(15)<<"speed" 74 <<setw(15)<<"wage"<<endl<<name<<setw(10)<<code 75 <<setw(15)<<speed<<setw(15)<<wage<<endl<<endl; 76 } 77 }; set_info("Ataur". 80 public: 81 void set_wage(float w){wage=w. 94 t.222). } 87 88 89 }. Rashed". 96 97 officer o.} 82 void show() 83 { 84 cout<<" name "<<setw(16)<<"code"<<setw(15)<<"speed" 85 <<setw(15)<<"wage"<<endl<<name<<setw(10)<<code 86 <<setw(15)<<speed<<setw(15)<<wage<<endl<<endl." Tata McGraw Hill").set_info("Md. 100 o.420). 98 99 o. t.set_details("programming with c++".set_details("First class"). 90 91 int main() 92 { 93 teacher t. 95 t.78 class causal:public typist 79 { float wage. 101 o. 102 .set_qualification("2 years experienced").set_qualification("PHD from programming "). set_info("Robiul Awal".show(). 116 117 cout<<" About regular typist :"<<endl. 108 ct. 119 cout<<" About causal typist :"<<endl. t.set_info("Kawser Ahmed".333).show(). 114 cout<<" About officer:"<<endl. 111 112 cout<<" 113 About teacher: "<<endl. 109 ct.9). 121 122 123 124 125 126 127 return 0.set_wage(15000). 103 rt. 104 105 106 rt. 118 rt.set_speed(85.show(). } .333). 115 o. rt.show(). 110 ct. 107 causal ct.regular rt. 120 ct.5).set_speed(78.set_wage(10000). Rashed code 222 Catagory Qualification First class 2 years experienced About regular typist : name Robiul Awal code 333 speed 85.5: Consider a class network of the following figure. Define all the four classes and write a program to create. The class master derives information from both account and admin classes which in turn derives information from the class person.900002 wage 10000 8.5 wage 15000 About causal typist : name Kawser code 333 speed 78. . update and display the information contained in master objects.128 129 130 131 132 133 134 O U T P U T About teacher: name code subject publication Ataur 420 programming with c++ qualification Tata McGraw Hill PHD from programming - About officer: name Md. Solution: 1 #include<iostream.n). public: 10 void set_info(char *n.h> 4 5 6 class staff { protected: 7 8 9 int code.int c) 11 { 12 strcpy(name.h> 3 #include<string. . char name[100].h> 2 #include<iomanip. public: 28 void set_details(char *s.strcpy(publication.code=c.publication[100]. 13 } 14 15 }.q). public: void set_qualification(char *q){strcpy(quali. 16 17 class education:public staff { 18 protected: 19 20 21 char quali[100].s). 31 32 } 33 34 35 36 void show() { cout<<"name"<<setw(8)<<"code"<<setw(15)<<"subject"<<setw(22) 37 <<"publication"<<setw(25)<<"qualification"<<endl<<name<<setw(8) .} 22 }.p). 23 24 class teacher : public education 25 { 26 27 protected: char sub[100].char *p) 29 { 30 strcpy(sub. g). 49 } 50 51 52 void show() { cout<<"name"<<setw(15)<<"code"<<setw(15)<<"Catagory" 53 <<setw(22)<<"Qualification"<<endl<<name<<setw(10) 54 <<code<<setw(15)<<grade<<setw(25)<<quali<<endl<<endl. public: .38 <<code<<setw(25)<<sub<<setw(18)<<publication<<setw(25)<<quail 39 <<endl. } 40 41 }. public: 46 void set_details(char *g) 47 { 48 strcpy(grade. 55 } 56 }. 57 58 class typist: public staff 59 { 60 61 62 protected: float speed. 42 class officer:public education 43 { 44 45 char grade[100]. } 73 void show() { 74 cout<<"name"<<setw(16)<<"code"<<setw(15)<<"speed"<<setw(15) 75 <<"wage"<<endl<<name<<setw(10)<<code<<setw(15)<<speed 76 <<setw(15)<<wage<<endl<<endl. 71 public: 72 void set_wage(float w){wage=w. 67 class regular:public typist 68 { 69 protected: 70 float wage. 65 } 66 }.void set_speed(float s) 63 { 64 speed=s.} 84 85 86 void show() { cout<<"name"<<setw(16)<<"code"<<setw(15)<<"speed"<<setw(15) 87 <<"wage"<<endl<<name<<setw(10)<<code<<setw(15)<<speed . 77 78 79 } }. class causal:public typist 80 { 81 float wage. 82 public: 83 void set_wage(float w){wage=w. 333).set_info("Ataur".set_qualification("PHD from programming ").set_details("First class"). . 106 causal ct." Tata McGraw Hill"). cout<<" About officer:"<<endl. 101 o.222). 110 cout<<" 111 112 About teacher: "<<endl.88 <<setw(15)<<wage<<endl<<endl.420).set_speed(85. 92 93 int main() { 94 95 teacher t. 104 rt.set_info("Kawser Ahmed".show(). officer o.set_details("programming with c++".set_wage(10000). 108 ct. 107 ct. Rashed". 109 ct. rt. 100 o.set_qualification("2 years experienced").set_speed(78.set_wage(15000). 102 103 o. t.set_info("Robiul Awal".5). t.333). regular rt. 105 rt.9). 96 97 98 99 t. t. } 89 90 91 }.set_info("Md. 3 the classes teacher. and typist are derived from the class staff. rt.113 o. officer and typist contain the objects of staff. Redesign the program of exercise 8. 115 cout<<" About causal typist :"<<endl. As we know we can use container classes in place of inheritance in some situations. 119 } 120 121 122 123 124 125 126 127 128 129 130 O U T P U T name Hasibul code 111 Experience 3 years payment 1500tk 8. Solution: .show().3 such that the classes teacher.show().show(). 116 ct. officer. 117 118 return 0.6: In exercise 8. 114 cout<<" About regular typist :"<<endl. publication[100].p). 13 code=c.s).h> 4 5 class staff 6 { public: 7 int code. 8 char name[100].h> 2 #include<iomanip. } 14 15}. public: void set_details(char *s. } void show() .int c) 11 { 12 strcpy(name.char *p) { 23 24 25 strcpy(sub.strcpy(publication. 9 public: 10 void set_info(char *n.h> 3 #include<string.n).1 #include<iostream. 16 class teacher : public staff 17 { 18 protected: 19 20 21 22 char sub[100]. 38 } 39 void show() 40 { 41 cout<<" name "<<setw(15)<<"code"<<setw(15)<<"Catagory "<<endl 42 43 <<name<<setw(10)<<code<<setw(15)<<grade<<endl.g). } 44}. 31 32 class officer:public staff 33 { 34 char grade[100]. public: . 35 public: 36 void set_details(char *g) 37 { strcpy(grade.26 { cout<<"name"<<setw(8)<<"code"<<setw(15)<<"subject"<<setw(25) 27 <<"publication"<<endl<<name<<setw(8)<<code<<setw(25)<<sub 28 <<setw(22)<<publication<<endl. 45 46class typist: public staff 47{ 48 49 50 protected: float speed. 29 } 30 }. t. 70 71 typist tp. 73 tp.set_info("Robiul Awal".333).set_details("programming with c++". Rashed".set_speed(85. 60 61 int main() 62{ 63 64 65 teacher t. 53 54 } void show() 55 { 56 cout<<" name "<<setw(15)<<"code"<<setw(15)<<"speed"<<endl 57 58 <<name<<setw(10)<<code<<setw(15)<<speed<<endl<<endl. t.420).set_info("Md. 66 67 officer o.set_info("Ataur". o. } 59}.set_details("First class"). .222).51 void set_speed(float s) 52 { speed=s. 68 69 o. 72 tp. 74 75 cout<<" About teacher: "<<endl." Tata McGraw Hill").5). tp. 78 cout<<" About 79 typist :"<<endl.7: We have learned that OOP is well suited for designing simulation programs. o.show().76 t.5 8.h> . 80 return 0. design a program that would simulate a simple real-world system familiar to you Solution: 1 #include<iostream. Rashed code 222 Catagory First class About typist : name Robiul Awal code 333 speed 85. Using the techniques and tricks learned so far.show(). 81 } 82 83 84 85 86 87 88 O U T P U T About teacher: name Ataur code 420 subject publication programming with c++ Tata McGraw Hill About officer: name Md.show(). 77 cout<<" About officer:"<<endl. 24 25 26 } cout<<"Enter roll: "."Sociology"."Higher Mathematics"}. gets(roll)."English 1st paper".h> 3 #include<string."Bangla 2nd paper". 8 "English 2nd paper".h> 4 5 #include<iomanip."Religion"."Mathematics".2 #include<stdio. 9 "Physics". 17 public: void set_info(). 18 19 }. .h> 6 7 char *sub[10]={"Bangla 1st paper". 23 gets(name)."Chemistry". 20 21 22 void student_info::set_info() { cout<<"Enter student name : ". 16 char roll[20].h> #include<conio. 10 11 class student_info 12 { 13 14 public: 15 char name[40]. i++) 40 { 41 cout<<sub[i]<<" = ? ".i<10. 35 }. 32 33 public: 34 void set_mark(). 43 } 44 45 } 46 class conversion :public subject 47 { 48 49 50 51 float gpa[10]. char grade[20][20]. 42 cin>>mark[i]. public: void convert_to_gpa().27 class subject :public student_info 28 29 { 30 public: 31 float mark[10]. . 36 37 void subject::set_mark() 38 { 39 cout<<" marks of : \n". for(int i=0. 69 strcpy(grade[i]."A"). void conversion::convert_to_gpa() 54 55 { for(int i=0. 70 71 72 } else if(mark[i]>=50 && mark[i]<60) { gpa[i]=3."A+").i++) 56 { 57 58 if(mark[i]>=80) { 59 gpa[i]=5.50.00. 74 } 75 else if(mark[i]>=40 && mark[i]<50) 76 { . 64 strcpy(grade[i].00.00. 60 strcpy(grade[i]."A-"). 52 53 }.i<10. 65 } 66 67 else if(mark[i]>=60 && mark[i]<70) { 68 gpa[i]=3."B").void show(). 73 strcpy(grade[i]. } 61 62 63 else if(mark[i]>=70 && mark[i]<80) { gpa[i]=4. ."Fail"). cout<<"Roll : "<<roll<<"\n".i<10. cout<<setw(25)<<"Subject"<<setw(17)<<"Marks" 97 <<setw(14)<<"GPA"<<setw(12)<<"Grade \n". 77 78 strcpy(grade[i]. 88 } 89 90 } } 91 92 void conversion::show() 93 { 94 95 96 cout<<" result of \n". 83 strcpy(grade[i]. 87 strcpy(grade[i]. cout<<"name :"<<name<<"\n".00. 98 99 for(int i=0.00.gpa[i]=2.00."D").i++) { 100 cout<<setw(25)<<sub[i]<<setw(15)<<mark[i] 101 <<setw(15)<<gpa[i]<<setw(10)<<grade[i]<<"\n". } 79 else if(mark[i]>=33 && 80 mark[i]<40) 81 { 82 gpa[i]=1."C"). } 84 else 85 { 86 gpa[i]=0. 113 } 114 115 116 117 118 119 120 121 122 O U T P U T Enter student name : santo Enter roll: 156271 marks of : Bangla 1st paper = ? 74 Bangla 2nd paper = ? 87 English 1st paper = ? 45 .} 102 103 } 104 105 int main() { clrscr(). 112 return 0. 110 A.set_mark(). 107 108 109 A.set_info(). 106 conversion A.show(). 111 getch(). A. A.convert_to_gpa(). English 2nd paper = ? 56 Mathematics = ? 87 Religion = ? 59 Physics = ? 75 Chemistry = ? 65 Sociology = ? 39 Higher Mathematics = ? 86 result of name :santo Roll : 156271 Subject Marks GPA Grade 4 A Bangla 1st paper 74 Bangla 2nd paper 87 5 English 1st paper 45 2 English 2nd paper 56 A+ C 3 B Mathematics 87 5 A+ Religion 59 3 B Physics 75 4 Chemistry 65 3.5 Sociology 39 1 Higher Mathematics 86 5 A AD A+ . 4: Explain. And we can achieve run time polymorphism by a mechanism known as virtual function. 9. Early binding means an object is bound to its function call at compile time. how you would create space for an array of objects using pointers.3: Discuss the different ways by which we can access public member functions of an object. 9. In details. with an example. 9. the statement item *ptr = new item [10]. // array of 10 objects. using operators or functions in different ways. Ans:We can access public member functions of an object by (i) Object name and dot membership operator. creates memory space for an array of 10 objects of item. and (b) run time? Ans:Polymorphism can be achieved at compile time by early binding. .Chapter 9: 9. (ii) Pointer to object and function name. For example.2: How is polymorphism achieved at (a) compile time.5: What does this pointer point to? Ans:‘this’ pointer point to invoking object. 9. polymorphism means one thing with several district forms. Ans:We can also create an array of objects using pointers. is called polymorphism. depending on what they are Operating on.1: What does polymorphism mean in C++ language? Ans:In short. (b) Virtual functions allow us to use the same junction call to invoke member functions of .10: State which of the following statements are TRUE or FALSE. inside a member function will return the object that invoked the function. 9. For example. The implications of making a function a pure virtual function is to achieve run time polymorphism. 9. we need virtual function.8: Why do we need virtual functions? Ans:It we need same function name at base class and derived class then.9: When do we make a virtual function “pure”? What are the implications of making a function a pure virtual function? Ans:When a function is defined as empty.6: What are the applications of this pointer? Ans:One important application of the pointer this is to return the object it points to. 9.9. (a) Virtual functions are used to create pointers to base classes. return * this.7: What is a virtual junction? Ans:When we use the same function name in both the base and derived classes the function in the base class is declared as virtual using the keyword virtual preceding its normal declaration. then this function is called do nothing function. the statement. 9. 4 int Number. Ans: (a) TRUE (b) TRUE (c) FALSE (d) TRUE (e) TRUE (f) TRUE (g) TRUE 9. (f) this pointer can be made to point to any object by assigning the address of the object. #include <iostream. (c) A pointer to a base class cannot be made to point to objects of derived class. (e) this pointer can be used like any other pointer to access the members of the object it points to. } }.h>. (d) this pointer points to the object that is currently used to invoke a function. 1 class Info 2 { 3 char* name. 8 getName().1: Identify the error in the following program. 5 public: 6 void getInfo() { 7 cout << "Info::getInfo". } }. 9 } 10 11 12 13 14 15 16 17 18 19 20 21 22 23 void getName() { cout << "Info::getName". . public: void getName() { cout << "Name::getName". class Name: public Info { char *name. (g) Pure virtual functions force the programmer to redefine the virtual function inside the derived classes.objects of different classes. 24 25 26 27 28 29 30 31 32 33 34 35 void main() { Info *P; Name n; P = n; p->getInfo(); } /* Solution: Here P=n will replace with P=&n in the main() function. Because P is a pointer. 9.2: Identify the error in the following program. #include <iostream.h>; 1 2 class Person { 3 int age; 4 public: 5 Person() 6 { } 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 Person(int age) { this.age = age; } Person& operator < (Person &p) { return age < p.age? p: *this; } int getAge() { return age; } }; void main() { Person P1 (15); Person P2 (11); Person P3; //if P1 is less than P2 P3 = P1 < P2; P1.lessthan(P2) cout << P3.getAge(); } /* 29 30 31 32 33 Solution: The function 1 person (int age) 2 { this.age = age; 3 } 4 should write like as… 1 person (int age) 2 { this > age = age; 3 } 4 9.3: Identify the error in the following program. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 #include <iostream.h>; class Human { public: Human() { } virtual -Human() { cout << "Human::-Human"; } }; class Student: public Human { public: Student() { } -Student() { cout << "Student::-Student()"; } }; void main() { Human *H = new Student(); delete H; } 27 28 29 30 Solution: Here we cannot write Human *H = new student(); in the main() function because base class’s member includes in derived class’s object so we should write this as follow student *H = new Student(); 9.4: Correct the errors in the following program. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 class Human { private: int m; public: void getdata() { cout << " Enter number:"; cin >> m; } }; main() { test T; T->getdata(); T->display(); test *p; p = new test; p.getdata(); (*p).display(); } Solution: Here T->getdata replace with T.getdata and T->display replace with T.display in the main() function. Because in this program T is object to pointer. 9.5: Debug and run the following program. What will be the output? #include<iostream.h> 1 class A 2 { 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 protected: int a,b; public: A(int x = 0, int y) { a = x; b = y; } virtual void print (); }; class B: public A { private: float p,q; public: B(intm, int n, float u, float v) { p = u; q = v; } B() {p = p = 0;} void input(float u, float v); virtual void print(loat); }; void A::print(void) { cout << A values: << a <<""<< b << "\n"; } void B:print(float) { cout << B values: << u <<""<< v << "\n"; } void B::input(float x, float y) { p = x; q = y; } main() { A a1(10,20), *ptr; B b1; b1.input(7.5,3.142); ptr = &a1; ptr->print(); ptr = &b1; ptr->print(); } h> class shape { public: 5 6 7 8 9 double x. Using these three classes.1: Create a base class called shape. Make display_area() as a virtual function and redefine this function in the derived classes to suit their requirements. and display the area. Add to the base class. Use this class to store two double type values that could be used to compute the area of figures. public: void get_data() { cin>>x>>y. Remember the two values given as input will be treated as lengths of two sides in the case of rectangles and as base and height in the case of triangles. 9. design a program that will accept dimensions of a triangle or a rectangle interactively. a member function get_data() to initialize base class data members and another member function display_area() to compute and display the area of figures.h> 1 2 3 4 #include<iomanip. Derive two specific classes called triangle and rectangle from the base shape. and used as follows: Area of rectangle = x * y Area of triangle = ½ * x * y Solution: #include<iostream. .49 50 51 52 Solution: The virtual keyword must write in base class and prototype base class and derived base class of print function should same.y. 33 cout<<" Area of rectangle = "<<a<<endl.} 12 double get_y(){return y. 32 a=x*y. 34 } . 23 24 } 25 }. 26 class rectangle:public shape 27 28 29 { public: void display_area() 30 { 31 double a. 22 cout<<" Area of triangle = "<<a<<endl. 21 a=(x*y)/2. 15 16 class triangle:public shape 17 { 18 public: 19 void display_area() 20 { double a.} 13 virtual void display_area(){} 14 }.10 } 11 double get_x(){return x. 44 s[0]->get_data().35 }. 41 rectangle r. 40 s[0]=&t. 39 triangle t. 42 s[1]=&r. 46 s[1]->get_data(). int main() 36 37 { 38 shape *s[2]. 43 cout<<" Enter the value of x & y for triangle: ". This requires addition of a new derived class ‘circle’ that computes the area of a circle. .2: Extend the above program to display the area of circles. 48 return 0. 49 } 50 51 52 53 54 O U T P U T Enter the value of x & y for triangle: 12 Enter the value of x & y for rectangle: 24 26 14 Area of triangle = 156 Area of rectangle = 336 9. 47 s[1]->display_area(). 45 cout<<" Enter the value of x & y for rectangle: ". s[0]->display_area(). its radius.) Solution: #include<iostream. for a circle we need only one value.double b) 9 { 10 x=a. 11 y=b. 12 } 13 double get_x(){return x.y.h> 1 2 3 4 #include<iomanip.} 15 virtual void display_area(){} 16 }.Remember.1416 class shape { 5 public: 6 double x.(Hint: Make the second argument of get_data() function as a default one with zero value. but the get_data() function in base class requires two values to be passed.} 14 double get_y(){return y. 7 public: 8 void get_data(double a. 17 18 19 20 21 class triangle:public shape { public: void display_area() .h> #define pi 3. 43 a=pi*x*x. 23 a=(x*y)/2. 45 46 } . 34 a=x*y. 24 cout<<" Area of triangle = "<<a<<endl. 35 cout<<" Area of rectangle = "<<a<<endl. 28 29 30 class rectangle:public shape { 31 public: 32 void display_area() { 33 double a.{ 22 double a. 44 cout<<" Area of circle = "<<a<<endl. 38 39 class circle:public shape { 40 public: 41 void display_area() 42 { double a. 25 26 } 27 }. 36 } 37 }. y). 61 double x. 69 cin>>rd.0).y. 62 63 64 cout<<" Enter the value of x & y for triangle: ". cout<<" Enter the value of x & y for rectangle: ".y). 68 double rd. cin>>x>>y.47 }. 58 59 circle c. 60 s[2]=&c. 71 cout<<endl<<endl. 55 56 57 rectangle r. cout<<" Enter the radius of circle : ". 66 67 s[1]->get_data(x. 52 53 triangle t. 65 cin>>x>>y. 48 49 50 int main() { 51 shape *s[3]. s[0]->get_data(x. . s[1]=&r. 54 s[0]=&t. 70 s[2]->get_data(rd. Solution: #include<iostream. (b) In addition to the above change. 76 } 77 78 79 80 81 82 83 O U T P U T Enter the value of x & y for triangle: 10 Enter the value of x & y for rectangle: 14 24 23 Enter the radius of circle : 12 Area of triangle = 120 Area of rectangle = 322 Area of circle = 452. Comment on the output in each case.h> 1 #include<iomanip. s[2]->display_area().72 s[0]->display_area().h> .3904 9. 73 s[1]->display_area(). 74 75 return 0.3: Run the program above with the following modifications: (a) Remove the definition of display_area() from one of the derived classes. declare the display_area() as virtual in the base class shape. y.} virtual void display_area(){} 15 }. } 24 25 }. 11 } 12 13 14 double get_x(){return x. 10 y=b.2 #define pi 3.1416 3 class shape 4 { public: 5 double x. 16 class triangle:public shape 17 { 18 public: 19 void display_area() 20 { 21 double a.} double get_y(){return y. 23 cout<<" Area of triangle = "<<a<<endl. 22 a=(x*y)/2. 6 public: 7 void get_data(double a. class rectangle:public shape 26 { .double b) 8 { 9 x=a. 41 42 } }. 30 a=x*y. 39 a=pi*x*x. 40 cout<<" Area of circle = "<<a<<endl. 49 s[0]=&t. 31 cout<<" Area of rectangle = "<<a<<endl. 43 44 int main() 45 { 46 47 shape *s[3]. 48 triangle t. 34 class circle:public shape 35 { public: 36 void display_area() 37 { 38 double a. 50 51 rectangle r. 32 33 } }. .public: 27 void display_area() 28 { 29 double a. 66 s[1]->display_area(). 68 69 70 71 72 73 74 75 76 return 0. 56 cin>>x>>y.y). 67 s[2]->display_area(). 55 cout<<" Enter the value of x & y for triangle: ".y). 64 cout<<endl<<endl.y. 59 cin>>x>>y. 53 circle c. 58 cout<<" Enter the value of x & y for rectangle: ". 65 s[0]->display_area(). cin>>rd.52 s[1]=&r. s[2]=&c. 60 s[1]->get_data(x. 57 s[0]->get_data(x. 54 double x. 63 s[2]->get_data(rd. 62 double rd. } . 61 cout<<" Enter the radius of circle : ".0). 64 .77 78 O U T P U T Enter the value of x & y for triangle: 28 32 Enter the value of x & y for rectangle: 25 36 Enter the radius of circle : 20 Area of triangle = 448 Area of rectangle = 900 Area of circle = 1256. Chapter 10: 10.1:What is a stream? Ans: The I/O system in C++ is designed to work with a wide variety of devices including terminals, disks and tape drives. Although each device is very different, the I/O system supplies an interface to the programmer that is independent of the actual device being accessed. This interface is known as stream. 10.2: Describe briefly the features of I/O system supported by C++. Ans: See table 10.1, page 293 of Balagurusamy. 10.3: How do the I/O facilities in C++ differ from that in C? Ans:We can design our own manipulators for certain special purposes in C++ but not in C. Example : 1 2 3 4 5 6 7 8 9 Ostream & unit (ostream & output) { output << “TK”; return output; } The statement cout << 100 << unit; will print 100 Tk. 10.4: Why are the words such as cin and cout not considered as keywords? Ans: cin and cout are related to iostream object, that’s why we must include iostream header file in our program to use cin and cout. Hence cin and cout are considered as iostream objects, not keywords. 10.5: How is cout able to display various types of data without any special instructions? Ans:The biggest single advantage to the stream methods is: they are type-safe. If you change a variable’s type, the sub sequent stream operations using that variable will either automatically accommodate the change, or will indicate an incompatibility at compile time. Thus cout is able to display various types of data without any special instructions. 10.6: Why is it necessary to include the file iostream in all our programs? Ans:Because any program has input or output statements and without iostream header file we can not use input or output statements, that’s why it is necessary to include the file iostream in all our programs. 10.7: Discuss the various forms of get() function supported by the input stream. How are they used? Ans:There are two types of get ( ) functions. We can use both get(char*) and get(void) prototype to fetch a character including the blank space. 10.8: How do the following two statements differ in operation? cin >> c; cin.get(c); Ans:cin>>c will read a character but it will skip the white space and new line character. cin.get (c); will read a character including white space and newline character. 10.9: Both cin and getline() function can be used for reading a string. Comment. Ans: cin reads a string and stops when a space or newline is encountered. getline ( ) function reads a whole line of text that ends with a newline character. 10.10:Discuss the implications of size parameter in the following statement: cout.write(line, size); Ans: cout.write (line, size) The first argument line represents the name of the string to be displayed and the secon d argument size indicates the number of characters to display. 10.11:What does the following statement do? cout.write(s1,m).write(s2,n); Ans: The statement cout.write(s1,m).write (s2,n); is equivalent to the following two statements; cout.write(s1,m); cout.write(s2,n); So, cout.write (s1,m).write (s2,n); will print two string s1 and s2 10.12: What role does the iomanip file play? Ans: The header file iomanip provides a set of functions called manipulators which can be used to manipulate the output formats. 10.13: What is the role of file() function? When do we use this function? Ans: fill ( ) is known as filling and padding function. The unused positions of the field are filled with white spaces, by default. We can use the fill ( ) function to fill the unused positions by any desired character. General form : cout.fill (ch); Example : cout.fill (‘*’); 10.14: Discuss the syntax of set() function. Ans: syntax of set function: cout.setf (arg1, arg2); here arg1 is one of the formatting flags and arg2 is bit field. Example: cout.setf (ios::left, ios :: adjust field); 10.15: What is the basic difference between manipulators and ioa member functions in implementation? Give examples. Ans: We can design our manipulator using manipulator function, which can not be done by ios member functions Example : 1 2 3 4 5 6 7 ostream & show (ostream & output) { output.setf (ios :: showpoint); output.setf(ios :: showpos); output << setw(10); return output; } This function defines a manipulator called show that turns on the flags showpoint and showpos declared in the class ios and sets the field width to 10. 10.16: State whether the following statements are TRUE or FALSE. (a) A C++ stream is a file. (b) C++ never truncates data. (c) The main advantage of width() junction is that we can use one width specification for more than one items. (d) The get(void) function provides a single-character input that does not skip over the white spaces. (e) The header file iomanip can be used in place of iostream. (f) We cannot use both the C 110 functions and C++ 110 functions in the same program. (g) A programmer can define a manipulator that could represent a set of format functions. 3: State errors.setf(ios::left).1:Sorry this question is missed.Ans: (a) TRUE (b) FALSE (c) FALSE (d) TRUE (e) TRUE (f) FALSE (g) TRUE 10.2: Will the statement cout. (c) cout << width(). (a) cout << (void*) amount.width(10). (e) cout.setf(ios::right) work or not? 1 2 3 4 5 6 7 8 9 10 11 12 13 #include <iostream. Stay with us 10. We will try to give this question with solution very soon.setf(ios :: right) will not work because width() function was not invoked before cout. cout << "99" << endl. } Solution: cout. cout. .h> void main() { cout.width(10).setf(ios::right). (d) int p = cout.width(5). (b) cout << put ("John") . cout << "99" << endl.precision(3). cout.setf(ios :: right) 10. cout << "99" << endl. if any.width(5). in the following statements. cout. Correction : cout. If you want to see output at left field you can achieve this as flows: cout.get(c).70 ……………… ………… …………… . (c) width ( ) function does not return any value.setf (ios :: scientific. must be written separately cout.1: Write a program to read a list containing item name. So cout <<="" p="" style="margin: 0px. so cout<<(“John”). Name Code Cost Turbo C++ 1001 250. (g) No error (h) cannot be concatenated. (k) cout << resetiosflags(ios::left lios::showpos).setf(ios::scientific.get(). (j) cout << setw(5) << setprecision(2). is not valid.get().get ( ) cin. (h) cin.width (10) precision (3).width (10). ios :: floatfield). ios :: adjustfield).preasion (3). (f) If you want to see output as scientfic format you can acheive this as follow: cout. (i) cin. item code. It is used to output a character.get ( ) (i) No error (j) No error (k) No error 10. (g) ch = cin. cout.ios::left).setf (ios :: left. (e) cout. and cost interactively and produce a three column output as shown below."> Correction : cout. Hence it does not return any value.get().put (‘John’). Correction : cin.get().width ( ). Solution: (a) missing (b) put ( ) a member function of ostream class. padding: 0px.95 C primer 905 95.(f) cout. Solution: 1 #include<iostream. 12 cost=co.ios::floatfield).setf(ios::fixed. . 11 code=c. 13 } 14 void display().n). 6 int code. 17 18 void item:: display() 19{ 20 cout. Trailing zeros are shown.int c.float co) 10 { strcpy(name.……………… ………… …………… Note that the name and code are left-justified and the cost is right justified with a precision of two digits. 7 float cost. 8 public: 9 void get_data(char *n. 21 cout.h> 2 #include<iomanip.h> 3 4 #include<string. 15 16 }.h> class item { 5 char name[40].precision(2). 1001.ios::adjustfield).i<60.7).ios::adjustfield). cout<<endl.i++) 37 38 cout<<"-". 34 35 a[3].905. 36 for(int i=0. 26 } 27 28 29 int main() { 30 item a[5].85). 39 for(i=0.1111. cout<<setw(10)<<"name"<<setw(34)<<"code"<<setw(15)<<"cost"<<endl.get_data("solution of balagurusamy".6666.get_data("Tarbo C++".setf(ios::right.22 cout. 25 cout<<setw(15)<<cost<<endl.120.150.95).setf(ios::showpoint).setf(ios::left.i<5.250. a[4].5).2220.145. 33 a[2].get_data("principle of electronics".get_data("C primer". 31 a[0]. 41 return 0.i++) 40 a[i].00).get_data("algorithm".display().95. 24 cout. 42} 43 44 45 46 . cout<<setw(40)<<name<<code. 23 cout. 32 a[1]. int c.h> 3 #include<string. 14 15 16 }.n). 12 code=c.70 C Primer algorithm 1111 Principle of electronics 120. 6 int code.2: Modify the above program to fill the unused spaces with hyphens. 8 public: 9 void get_data(char *n. 17 } void display().O U T P U T name code cost ————————————————————————————— Tarbo C++ 1001 250.h> 4 class item 5 { char name[40].00 10.h> 2 #include<iomanip. 13 cost=co.85 145. 7 float cost. .float co) 10 { 11 strcpy(name. Solution: 1 #include<iostream.95 905 95.50 2220 Solution of balaguruswamy 6666 150. cout<<setw(10)<<"name"<<setw(34)<<"code"<<setw(15)<<"cost"<<endl. 34 35 36 37 38 39 40 41 42 a[2].7).905.1111.i<60.5).fill('-').ios::floatfield).2220. 33 a[1]. for(i=0.00).get_data("C primer". 24 cout.i<5. cout<<endl.120.i++) cout<<"-".display().setf(ios::right. a[3]. 25 cout<<setw(40)<<name<<code.85).get_data("principle of electronics".precision(2).95).1001. cout.get_data("Tarbo C++".setf(ios::fixed.18void item:: display() 19{ 20 21 cout. a[0].setf(ios::left. 26 cout. 27 cout<<setw(15)<<cost<<endl.6666.setf(ios::showpoint).145.95. for(int i=0. . 22 cout.i++) a[i].150. 23 cout. a[4].get_data("solution of balagurusamy".ios::adjustfield).get_data("algorithm".ios::adjustfield).250. 28 } 29 30 int main() 31 { 32 item a[5]. h> 4 5 6 7 8 int main() { char line[1000]. 43 44} 45 46 47 O U T P U T name code cost ————————————————————————————— Tarbo C++ ——————– 1001———–250. .h> #include<string.return 0.h> #include<stdio.85 Solution of balaguruswamy–6666——— 145.95 C Primer ———————-905————-95.70 algorithm———————-1111————120.50 Principle of electronics ——2220———–150.h> 1 2 3 #include<iomanip.3: Write a program which reads a text from the keyboard and displays the following information on the screen in two columns: (a) Number of lines (b) Number of words (c) Number of characters Strings should be left-justified and numbers should be right-justified in a suitable field width.00 10. Solution: #include<iostream. char ch. 28 } 29 lines++. 19 line1='\0'.9 int c.setf(ios::left.lines. word=0. 12 chr=0. 14 cout<<" Enter text : \n". 15 while(end==0) 16 { 17 c=0. 30 31 chr+=strlen(line).chr. 20 if(line[0]=='\0') 21 break.ios::adjustfield). 11 lines=0.i++) 26 27 if(line[i]==' ' || line[i]=='\t' || line[i]=='\n') word++. } 32 33 cout. 10 int word. . 25 for(int i=0.line[i]!='\0'. 13 int end=0. while((ch=getchar())!='\n') 18 line1=ch. 22 else 23 { 24 word++. Number of lines 5 Number of words 25 Number of characters 128 Note: If you press the Enter button two times. He respects his teachers.setf(ios::right. I like his morality. 35 cout.ios::adjustfield). He feels shy when I admire him. 37 return 0. the program will terminate. . 36 cout<<setw(10)<<lines<<setw(24)<<word<<setw(25)<<chr<<endl<<endl. He always speak the truth.cout<<setw(25)<<"Number of lines"<<setw(25) 34 <<"Number of words "<<"Number of characters "<<endl. 38 } 39 40 41 42 O U T P U T Enter text : santo reads in class five. The input stream extracts data from the file and output stream inserts data to the file.Chapter 11: 11.1: What are input and output streams? Ans:The stream that supplies data to the program is known as input stream and one that receives data from the program is known as output stream.4: What is the difference between opening a file with a constructor function and opening a file with open() function? When is one method preferred over the other? .3 of Balagurusamy. Ans:See fig 11. 11.2: What are the steps involved in using a file in a C++ program? Ans:The I/O system of C++ handles file operations which are very much similar to the console input and output operations. 11. Page-325 11.3: Describe the various classes available for file operations. Ans:When we open a file with a constructor a file name must be supplied during creation of object. constructor method is proffered for only one file in the stream. stream-object open (“file name”. outfile. 11. returns a value of o if any error occurs in the file operation including the end-of-file condition. But when we use open ( ) function we can provide file name later. Various file mode options : Parameter ios::app ios::ate ios::binary ios::in ios::nocreate ios::noreplace ios::out Meaning Append to end of file Go to end of file on opening Binary file open file for reading only open fails if the file does not exist open fails if file already exist open file for writing only. mode).5: Explain how while(fin) statement detects the end of a file that is connected to fin stream Ans:The given statement is while (fin) An ifstream object. member function open ( ) of the class is preffered when we want to manage multiple files using one stream. Example : ofstream outfile. Thus end of file is detected. Another difference is we can provide file modes using open ( ) function. Ans: File-mode specifies the purpose for which the file is opened. such as fin. 11. We know while loop will terminate when fin returns zero.6: What is a file mode? Describe the various file mode options available. Example : ofstream outfile (“result”).open (“Result”). //output only. . 11.10: What does the “current position” mean when applied to files? Ans: The ‘curren position’ applied to file means the byte location at which the next read or write operation will take place. 11. fob.7: Write a statement that will create an object called fob for writing.8: How many file objects would you need to create to manage the following situations? (a) To process four files sequentially. 11.ios::trunc Delete the contents of the file if it exist.open (“DATA”). (b) In such case we need to create two separate input stream for handling the two input files and one output stream for handling the output file.11: Write statements using seekg() to achieve the following: (a) To move the pointer by 15 positions backward from current position. Ans: (a) only a single stream object. While ios::ate mode permits us to add data or to modify the existing data anywhere in the file. That means require three stream object. (b) To go to the beginning after an operation is over. The difference between the two parameters is that the ios::app allows us to add data to the end of the file only. .9: Both ios::ate and ios::app place the file pointer at the end of the file (when it is opened). Explain. is the difference between them? Ans: Both ios::ate and ios::app take us to the end of the file when it is opened. What then. 11. and associate it with a file name DATA Ans: ofsteam fob. 11. (b) To merge two sorted files into a third file. ios::end). . If end of file occurs fin returns zero. When do you need such information? Ans: We can find out the total number of objects in a file using object_length as follows: in n = file_size/object_length.15: State whether the following statements are TRUE or FALSE.seekg(0. Ans: Let. Modify an existing item 3.seekg (-15. Display the contents of a file. (d) fout.seekg (49. 2.ios::cur). Deleting an existing item 11. (a) fout. 11.12: What are the advantages of saving data in binary form? Ans: The binary format is more accurate for storing the numbers as they are stored in the exact internal representation. 11. (d) To go to byte number 50 in the file.seekg (-20. Ans: Let. There are no comuensions while saving the data and therefore saving is much faster read ( ) and write ( ) function do this job.13: Describe how would you determine number of objects in a file. (b) fout.ios::beg). (c) fout. fin be an object of if stream.14: Describe the various approaches by which we can detect the end•of-file condition successfully. This information is required to 1. So we can use while (fin) to detect end of file.(c) To go backward by 20 bytes from the end. fout be an ofstream object. Adding new item 4. 11.ios::beg). 11. (b) finl. Stay tune with us..3 is unfortunately missed.wrttel(char *) & obj. (d) The ios::ate mode allows us to write data anywhere in the file. (e) We can add data to an existing file by opening in write mode. Ans: (a) FALSE (b) FALSE * file pointer can be a synonym for current position. (g) The data written to a file with write) function can be read with the get() function. writes only data in obi to outfit.fail()call returns non-zero when an operation on the file has failed.fail ( ) cau returns non-zero when an input or output operation on the file has failed. //finl is input stream (c) if(finl. (j) The fin.2 and 11. We will come back with this question and answers very soon. NOTE: We are sorry to say that Debugging Exercise question no 11.eof() == 0) exit(1).(a) A stream may be connected to more than one file at a time. (c) The statement outfile. (c) TRUE (d) TRUE (e) TRUE (f) TRUE (g) FALSE (h) FALSE * tell ( ) is for output file and tell g ( ) for input file (i) TRUE (j) FALSE * fin. (a) ifstream. .4: Find errors in the following statements.getline(). (h) We can use the functions tellp() and tellg() interchangeably for any file. Happy coding 11. (i) Binary files store floating point values more accurately and compactly than the text files.sizeof(obj)).infile(“DATA”). (b) A file pointer always contains the address of the file. (d) close(f1). (f) The parameter ios::app can be used only with the files capable of output.1 . h> #include<fstream.(e) infile.open(argc).open (argv[1]) : (f) The argument file must write as ” file” because this is string type.open (“file”. it input only one character from file and then it will exit. 11.h> 2 #include<stdio. sfinout. ios::inios::out. eof ( ) = = 0) exit (1). (g) sfinout.1 Write a program that reads a text file and creates another file that is identical except that every sequence of consecutive blank spaces is replaced by a single space. Solution: 1 #include<iostream. Solution: (a) Error : Improper use of ifstream.h> 3 #include<string.open(file. Correction : ifstream infile (“DATA”). 20).h> 4 5 int main() . Such as char s[20]. getline(s. ios::ate). (b) Here you must give two argument for getline ( ) function one is string type variable name and another is string size. Correction : fstream sfinout. (d) close ( ) is void type argument function so it will be fl.close ( ) (e) argc is called argument counter and agrv is called argument vector so to open data file we can write the statement like this: infile. (c) If we write if (fin1.ios::in |ios::out| ios::ate). 11 // retrieve a single character fro file. 7 // of is a object of of. 25 } 26 } 27 28 29 30 of<<" ". if(c!=' ') // is character is no space? { // If yes go outsi while loop. 9 ifstream inf("santo. // write next charcter to “hasib” te . // this is just for sk space.get(c). // open a text document file named “santo” 10 inf.txt"). 24 break.6 { ofstream of.txt").open("hasib.get(c). 8 ofstream file. 21 23 // is character is ‘/0’ { 19 22 execute “if” { 18 20 // is character is a space? If yes statement. // open a text document file named “hasib” to writ char c. of<<c. 12 while(inf) 13 // is character is ‘/0’ ? if not go inside loop { 14 15 16 if(c==' ') 17 while(inf) ? if not go in inf. document file. // write single space to “hasib” te document file. // retrieve a single characte “santo” file. get(c). 33 34 inf.h> 1 2 #include<fstream. The names should be left justified and the numbers should be right justified. 36 } Note: Before you run this program you just create a ‘.h> 4 5 6 7 8 int main() { char name[100].txt’ document to a particular drive where your compiler was installed.} 31 else 32 of<<c. . Write program to read this file and output the list in two columns.h> #include<string. 11.h> 3 #include<iomanip. 35 } return 0. // write single character where no space exi // retrieve a single character from “santo” text again.n[100]. Solution: #include<iostream.2 A file contains a list of telephone numbers in the following form John 23456 Ahmed 9876 …………… ………… the names contain only one word and the names and telephone numbers are separated by white spaces.number[100]. 18 19 } 20 else 21 { 22 if(santo. 12 13 again: 14 santo>>name.txt’ document like as question no 11. 26 } 27 28 return 0. } 29 30 Note: You just create a ‘. cout<<" Enter your desired name to find mobile number :" .100).n)) { 16 santo. O U T P U T .txt").ifstream 9 10 santo("robin.1 which contains peoples name and phone number.getline(number. else 25 goto again.eof()!=0) 23 24 cout<<" Sorry your input name is not found in list \n". 15 if(!strcmp(name. 11 cin>>n. 17 cout<<setw(-20)<<name<<setw(25)<<number<<"\n". "+455652132"}. char *name[size]={"sattar". Solution: 1 2 #include<iostream. 10 11 12 13void phone:: set_data() 14{ 15 16 ofstream santo("phone.3 Write a program that will create a data file containing the list of telephone numbers given in exercise in 11.Enter your desired name to find mobile number : john john 23456 11."robin".2.txt")."kawser"}. 17 18 19 char *number[size] ={"01673050495". Use a class object to store each set of data.h> #define size 5 3 4 class phone 5 { 6 public: 7 void set_data().h> #include<fstream."kamruzzaman"."santo". 8 9 }."+214324513"."01818953250". ."01723783117". ios::adjustfield). } 28} 29 30int main() 31{ 32 33 phone book. menu-driven program that will access the file created in exercise 11. 26 27 santo<<number[i]<<"\n".i<size. (c) Update. (b) Determine the name if a telephone number is known.set_data(). 34 return 0.setf(ios::right. . 22 santo.setf(ios::left.width(20). book. whenever there is a change.ios::adjustfield). 11. 23 santo<<name[i].4 Write an interactive.3 and implement the tasks: (a) Determine the telephone number of the specified person. It will create a txt document named ‘phone’.20 for(int i=0.width(15). 25 santo. 35 } 36 37 38 Note: When you run this program.i++) { 21 santo. 24 santo. the telephone number. n[100]. again1: 22 santo>>name.number[100]. int test.h> 5 int main() 6 { 7 char name[100].h> 1 2 3 4 #include<fstream. 8 9 ifstream 10 santo("robin.h> #include<string.Solution: #include<iostream. cout<<"\n". 23 if(!strcmp(name.txt").n)) .m[100]. to find name of specified number \n" cin>>test.h> #include<iomanip. 11 cout<<" Press 1 to find mobile number of specified person\n " 12 <<" Press 2 13 <<" Press 3 to update number \n" 14 <<" What is your option ?: ". 19 20 21 cin>>n. 15 16 17 if(test==1) { 18 cout<<" Enter the desired name : ". getline(number. . 44 cout<<"\n". else 33 goto again1.100). 34 } 35 36 } 37 38 39 40 41 else if(test==2) { 42 cout<<" Enter the desired number : ". 43 cin>>n. 45 again2: 46 47 48 santo>>name. 25 cout<<setw(-20)<<name<<setw(25)<<number<<"\n". santo>>number.{ 24 santo.eof()!=0) 31 32 cout<<" Sorry your input name is not found in list \n". 26 27 } 28 else 29 { 30 if(santo. 61 } 62 } 63 else if(test == 3) 64 { 65 ofstream hasib("modified. 67 cin>>n.txt"). 66 cout<<"Enter the name whose number have to change : ".name)) 71 { 72 cout<<" Enter changed mobile number 73 of"<<name<<": ".n)) 49 { 50 51 cout<<setw(-20)<<number<<setw(25)<<name<<"\n". . 59 else 60 goto again2. 52 53 } 54 else 55 { 56 if(santo. 69 70 if(!strcmp(n.eof()!=0) 57 58 cout<<" Sorry your input number is not found in list \n". 68 again3: santo>>name>>number.if(!strcmp(number. 94 else 95 96 { hasib.setf(ios::left.74 cin>>m. hasib<<name.width(15). 84 hasib.setf(ios::right.setf(ios::right.setf(ios::left.ios::adjustfield). 83 hasib.ios::adjustfield). 76 hasib<<name. 78 hasib.width(20).eof()!=0) 93 cout<<" Sorry your input name is not available \n".setf(ios::left. hasib.setf(ios::right. 77 hasib. 85 hasib. 87 hasib<<number<<"\n".ios::adjustfield). 97 hasib<<name. 80 while(santo) 81 { 82 santo>>name>>number. 88 } 89 90 91 } else { 92 if(santo. 86 hasib.width(20). 98 hasib. 79 hasib<<m<<"\n". 75 hasib. hasib.width(15).ios::adjustfield). .ios::adjustfield).ios::adjustfield).width(20). goto again3. 100 hasib<<number<<"\n".width(15). } 109 110 111 112 113 114 115 116 During First Run : O U T P U T Press 1 to find mobile number of specified person Press 2 to find name of specified number Press 3 to update number W hat is your option ?: 1 Enter the desired name : john john 23456 . 101 } 102 } 103 104 105 } 106 107 108 return 0.99 hasib. During Second Run : O U T P U T Press 1 to find mobile number of specified person Press 2 to find name of specified number Press 3 to update number W hat is your option ?: 3 Enter the name who se number have to change : Ahmed Enter changed mobile number of Ahmed : 9876 .
Copyright © 2024 DOKUMEN.SITE Inc.