Concept explainers
Reread the code in Display 10.9. Then, write a class TwoD that implements the two-dimensional dynamic array of doubles using ideas from this display in its constructors. You should have a private member of type pointer to double to point to the dynamic array, and two int (or unsigned int) values that are MaxRows and MaxColS.
You should supply a default constructor for which you are to choose a default maximum row and column sizes and a parameterized constructor that allows the programmer to set maximum row and column sizes.
Further, you should provide a void member function that allows setting a particular row and column entry and a member function that returns a particular row and column entry as a value of type double.
Remark: It is difficult or impossible (depending on the details) to overload ( ) so it works as you would like for two-dimensional arrays. So simply use accessor and mutator functions using ordinary function notation.
Overload the + operator as a friend function to add two two-dimensional arrays. This function should return the TwoD object whose ith row, jth column element is the sum of the ith row, jth column element of the left-hand operand TWOD object and the ith row, jth column element of the right-hand operand TwoD object.
Provide a copy constructor, an overloaded operator z, and a destructor.
Declare class member functions that do not change the data as const members.
Program Plan:
- Define class named as TwoD and declare the variables for rows and columns.
- Declare a variable of pointer to double to point to the dynamic array.
- Define the default constructor and parameterized constructor to initialise rows and columns.
- Define the copy constructor that copies the values of one object array to another object array.
- Define operator + function declared as friend that add two dimensional arrays and return the sum.
- Use the setValue () function to set the values in the matrices m1 and m2 of double type.
- Finally write the main function to test the class TwoD.
Program Description:The purpose of the program is to set the values of two matrices of double type and add them to print the third matrix using the class TwoD and its constructors.
Explanation of Solution
Program:
//header files #include <iostream> usingnamespacestd; //Create Class TwoD classTwoD { //Private Data members private: intMaxRows; intMaxCols; //Declare array double&Twoarr; //Access Specifier public: //Create Default Constructor TwoD() { //chooses default rows and columns MaxRows=10; MaxCols=10; Twoarr=newdouble*[MaxRows]; for(int it =0; it <MaxRows;++it) { Twoarr[it]=newdouble[MaxCols]; } } //Create parameterised Constructor for setting the rows and columns TwoD(int rows,int cols) { //chooses Default rows and columns MaxRows= rows; MaxCols= cols; Twoarr=newdouble*[MaxRows]; for(int it =0; it <MaxRows;++it) { Twoarr[it]=newdouble[MaxCols]; } } //included the copy constructor TwoD(constTwoD&matrix) { //rows and columns assigned to the constructor object MaxRows=matrix.MaxRows; MaxCols=matrix.MaxCols; Twoarr=newdouble*[MaxRows]; for(int it =0; it <MaxRows;++it) { Twoarr[it]=newdouble[MaxCols]; for(intjt=0;jt<MaxCols;++jt) { Twoarr[it][jt]=matrix.Twoarr[it][jt]; } } } //Destructor ~TwoD() { for(int it =0; it <MaxRows;++it) { delete[]Twoarr[it]; } deleteTwoarr; } //member function for setting the values voidsetValue(int row,int col,doubleval) { Twoarr[row][col]=val; } //Friend function which overloads the "+" Operator friendTwoDoperator+(TwoD&m1,TwoD&m2) { TwoD*m3 =newTwoD(m1.MaxRows, m1.MaxCols); for(int it =0; it < m3->MaxRows;++it) { for(intjt=0;jt< m3->MaxCols;++jt) { //Performs addition m3->Twoarr[it][jt]= m1.Twoarr[it][jt]+ m2.Twoarr[it][jt]; } } return*m3; } //Void function to print the values void print() { for(int it =0; it <MaxRows;++it) { for(intjt=0;jt<MaxCols;++jt) { cout<<Twoarr[it][jt]<<""; } cout<<endl; } } }; intmain() { //declare variables intmaxRows; intmaxColumns; //Getting inputs from the user cout<<"Enter row Dimensions of the array:"<<endl; cin>>maxRows; cout<<"Enter Column Dimensions of the array:"<<endl; cin>>maxColumns; cout<<"&********************************"**lt;<endl; cout<<"Echoing the two-dimensional Array"<<endl; cout<<"&********************************"**lt;<endl; //passing parameters to the class objects TwoDm1(maxRows,maxColumns); TwoDm2(maxRows,maxColumns); for(int it =0; it <maxRows;++it) { for(intjt=0;jt<maxColumns;++jt) { m1.setValue(it,jt,0.2*(it +jt)); m2.setValue(it,jt,0.3*(it -jt)); } } //printing the results cout<<"&***********"**lt;<endl; cout<<"Matrix 1 "<<endl; cout<<"&***********"**lt;<endl; m1.print(); cout<<"&***********"**lt;<endl; cout<<"Matrix 2"<<endl; cout<<"&***********"**lt;<endl; m2.print(); //performs the addition operation TwoD m3 = m1 + m2; cout<<"&***********"**lt;<endl; cout<<"Addition "<<endl; cout<<"&***********"**lt;<endl; m3.print(); return0; }
Explanation:
First, TwoD class is defined along with all the required variables and constructors. Then, from the main ()function, the instances of the class is called, the rows of the array and the column of the array are entered by the user.
The two dimensional array is echoed randomly. Two matrices of given order are generated. The sum of these two matrices are obtained and displayed on the output screen.
Output Screenshot:
Want to see more full solutions like this?
Chapter 10 Solutions
Absolute C++
Additional Engineering Textbook Solutions
Starting Out with Programming Logic and Design (4th Edition)
Starting Out with Java: From Control Structures through Data Structures (4th Edition) (What's New in Computer Science)
Introduction to Java Programming and Data Structures, Comprehensive Version (11th Edition)
Problem Solving with C++ (10th Edition)
Starting Out with Python (4th Edition)
Java How To Program (Early Objects)
- Create a Vector2D class with properties x and y and a proper constructor method. Plus, minus and multiplication with a scalar operators should be overloaded. Create a Body class with properties of pos, vel, mass and constructor(float Mass, Vector2D Pos, Vector2D Vel), addForce(Vector2D F) and Move(float dt) methods. Your program should create an array or collection of Bodies, at each time step (dt), calculate forces that bodies exert each other and apply accordingly. Finally, in a 2D space, bodies should move freely based on their properties and applied forces. You can use option buttons or another element to represent bodies and move them inside the form.arrow_forwardYour task is to create a class name polygon that contains 2 data members i.e. length of type float and width (a pointer of type float). Create a single object named “one” in the main and assign values to the data member of the polygon object. Then create another object named “two” that is a copy of the “one”. Create a shallow copy constructor that copies only the pointer data member of the class polygon and then demonstrate that both objects share a common memory i.e. modifying one object in fact modifies the other.Create a display function that will show the values of the polygon object.arrow_forwardin c++ . Create a class IntegerSet for which each object can hold integers in the range 0 through 100. A set is represented internally as an array of ones and zeros. Array element a[ i ] is 1 if integer i is in the set. Array element a[ j ] is 0 if integer j is not in the set. • The default constructor initializes a set to the so-called “empty set,” i.e., a set whose array representation contains all zeros. • Provide member functions for the common set operations. For example, provide a unionOfSets member function that creates a third set that is the settheoretic union of two existing sets (i.e., an element of the third set’s array is set to 1 if that element is 1 in either or both of the existing sets, and an element of the third set’s array is set to 0 if that element is 0 in each of the existingsets). Provide an intersectionOfSets member function which creates a third set which is the set theoretic intersection of two existing sets (i.e., an element of the third set’s array is set…arrow_forward
- Create a class Department with attributes DName, DID, a dynamic listDTeachers of type string.Write accessors and mutators for all data membersand show function to show all data members.Create nullaryand parameterized constructors to initialize the data members.Also write a copy constructor for Department class.In main() create a dynamic array of departments, Use loop to create four objects in the dynamic array. All the even indexed objects should be created with nullary constructors and thencall the accessors and mutators to initializethe objects while, all the odd indexed objects should be initialized using parameterized constructors. Create four copy objects from array using copy constructors.Call the show function to show the four objects.arrow_forwardIN C++ In your previous class, move the member variables (student name and grades) as private. Create the proper functions to fill data in them. In main, create an instance of that array and fill that instance with data. Call the DisplayInfo() function from main so it prints the content of the object. A screenshot showing the code in Visual Studio and the output (on the console screen). previous activity class code:- #include <iostream>using namespace std;class student{ public: string Name; string grade[3]; void DisplayInfo() { cout<<"Student Name:"<<Name; cout<<"\nGrade:"<<grade[1]; }};int main(){ cout << "Welcome to my world..." << endl; system("pause"); student obj; obj.Name="Rahul"; obj.grade[1]="A++"; obj.DisplayInfo(); return 0;}arrow_forwardWrite a Program to define a Mobile class, with member variables String brand; double price String OS (make it Final). Float memory Make a default constructor, Make a parameterized constructor. Overload the above Constructor. Provide getters and setters for data members. Inside main, create an array of mobiles. Take data from user and set the values for the mobiles in array (check for array out of bound exception). At the end Print data of array using Loop.arrow_forward
- Create a class: Question 1 with data members: 1D integer array of maximum size: 100, n (int). Create a dynamic constructor which takes input of n and n no. of array elements. Apart from taking input this class also displays the maximum and minimum elements from the given array elements.arrow_forwardthis question is related to subject object oriented programming in c++ language. solve given question in dev c++ software. kindly send answer quickely. Question: Write a class named ExamScore that has the following member variables and functions. Protected Variables : char name[10], double *testscore , int subjects, double sum Functions: Setscore (index, marks) // it will store the marks at particular index in array. Findtotal() // it will find the sum of all the marks in array and stores it in sum variable. Displayscores()// it will display all the scores. Derive a class Result from ExamScore Class publically that has the following member variables and functions. Private Variables Max Functions: constructor (name,subjects) to initialize name and subjects variables. It will also initialize *testscore array dynamically by assigning it memory locations equal to subjects variable. Maximum () // it will find the maximum score in testscore array and stores it in Max variable.…arrow_forwardWrite in c++ language: Your program will have a class called FlightController that is going to be derived from twobase classes which are called LaunchController and LandingController. The FlightControllerclass inherits all accessible data fields and methods from the LandingController andLaunchController classes.Inside the FlightController class, you will define an object of type FlightSchedule which willcontain an array of 3 objects of type Flight. In your Flight objects, the constructor of theseobjects will ask from the user for the inputs of: flight name, launch hour, launch minutes,flight duration. The value of state of the Flight object will be assigned to “Idle” as a defaultvalue in the constructor also and you will call the member function within the Flight classwhich will calculate the landing time for your flight object by using the duration and thelaunch time. Definition of Flight class will also contain the necessary getters and setters thatare given in the diagram and needed…arrow_forward
- Define a class named VectorDouble that mimics a vector with double type. Your class should have following members: - A pointer of double type to point to a dynamic array. - An int named _size to track how many elements in the array. - An int named _capacity to track the capacity (maximum size of the array). - A default constructor that creates a dynamic array with 10 spots/capacity. - A parameterized constructor that creates a dynamic array with given capacity. - A copy constructor. - A copy assignment operator. - A destructor. - An overloaded operator << to output all numbers in the array. - A member function push_back() that adds a new number to next available spot in the array. - A member function pop() that removes last element in the array. - A member function back() that returns last element in the array. - A member function size() that returns the current size of the array. - A member function capacity() that returns the capacity…arrow_forwardWrite a class with name intlist. This class will have an integer array arr (for simplicity define it with 100 locations) and an integer ent as member data in private section. cnt variable will be used to keep the number of elements in integer array (arr). In public section of this class there will be following member functions with explained tasks: (i) (ii) (iii) (iv) (v) :returns the number of elements in arr array listcount() addfirst(x) : locates integer x to the first position of arr. All current elements in array will move to the next location. addlast(x) : locates integer x to the last free location. removeall(): remove all elements of array removefirst(): remove first element of array. All current elemets in array will move to the preceding location (vi) removelast(): remove last element of array. (vii) remove(i) : remove element in index i. Notice: While adding if maximum exceeds will give an error message. While removing if there is no element or if there is no elements in…arrow_forwardYou are required to design an BeautyProduct class which has following attributes String name; String brand; Double price; Double quantity; String expiry_Date; 1. Provide default & Parameterized constructors. 2. Provide getters & setters for data members. 3. Provide a toString() method to print values. Now create an array of BeautyProduct in a class Salon having name and address as attributes as well, Provide appropriate methods, store values in array (take values form user). Provide a buy method which will ask user to buy a BeautyProduct by providing its name, check that it is present or not then ask for quantity and create bill for user. After that you have to print the following 1. View all products. 2. Buy Product. 3. Product of brand “Mac”; 4. Product with highest price. 5. All the products having expiry date before 1-3-2022. Programming language :Javaarrow_forward
- Database System ConceptsComputer ScienceISBN:9780078022159Author:Abraham Silberschatz Professor, Henry F. Korth, S. SudarshanPublisher:McGraw-Hill EducationStarting Out with Python (4th Edition)Computer ScienceISBN:9780134444321Author:Tony GaddisPublisher:PEARSONDigital Fundamentals (11th Edition)Computer ScienceISBN:9780132737968Author:Thomas L. FloydPublisher:PEARSON
- C How to Program (8th Edition)Computer ScienceISBN:9780133976892Author:Paul J. Deitel, Harvey DeitelPublisher:PEARSONDatabase Systems: Design, Implementation, & Manag...Computer ScienceISBN:9781337627900Author:Carlos Coronel, Steven MorrisPublisher:Cengage LearningProgrammable Logic ControllersComputer ScienceISBN:9780073373843Author:Frank D. PetruzellaPublisher:McGraw-Hill Education