C++ Create a NumberList class which has a dynamic integer array with size initia
ID: 3710933 • Letter: C
Question
C++
Create a NumberList class which has a dynamic integer array with size initially unknown. Create an object from this class, ask the user for size of the array in the object, dynamically create it and fill it with random numbers. Then create two more objects and set them to the first object. Replace all odd numbers with their negatives in the second object and replace all even numbers with their negatives in the third object. Print all three arrays on screen. Copy constructor is needed for this question.
Explanation / Answer
Here is the required code for this problem:
#include<bits/stdc++.h>
#include <cstdlib>
using namespace std;
class NumberList
{
public:
int *arr=NULL; // Dynamic array
};
int main()
{
NumberList obj1; // First object
cout<<"Enter the size of an array"<<endl;
int n;
cin>>n;
obj1.arr=new int[n]; // Assigning size to dynamic array
int *arrc=obj1.arr;
int rand(); // defining random function
for(int j=0;j<n;j++)
{
int temp=rand()%10;
*(arrc+j)=temp;
}
cout<<"First Array:"<<endl;
for(int j=0;j<n;j++)
{
cout<<*(obj1.arr+j)<<endl;
}
NumberList obj2; // creating second object
obj2.arr=obj1.arr; //setting them to the first object
for(int j=0;j<n;j++)
{
if(*(obj2.arr+j)%2!=0)
*(obj2.arr+j)=-1*(*(obj2.arr+j));
}
cout<<"Second Array: odd numbers"<<endl;
for(int j=0;j<n;j++)
{
cout<<*(obj2.arr+j)<<endl;
}
NumberList obj3; // creating third object
obj3.arr=obj1.arr; //setting them to the first object(Copying values)
for(int j=0;j<n;j++)
{
*(obj3.arr+j)=-1*(*(obj1.arr+j));
}
cout<<"Third Array: even numbers"<<endl;
for(int j=0;j<n;j++)
{
cout<<*(obj3.arr+j)<<endl;
}
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.