A class newType is defined as in the following program. Complete the program by:
ID: 3836011 • Letter: A
Question
A class newType is defined as in the following program. Complete the program by: in the constructor, use the pointer p to dynamically allocate an array with 10 integers, assign the array with random numbers within [0, 20]. The member function fun() requires an integer parameter n, the function calculates and returns the product of all odd numbers in the array that are greater than n; deallocates the array in the destructor. In main(), use newType to declare a variable and call its fun() to print the product (while calling the function, pass an integer less than 10). #include using namespace std; class newType//Part I class definition { private: int *p; public: newType(); ~newType();Explanation / Answer
Program.cpp
------------
#include <iostream>
#include <new>
#include <stdlib.h>
using namespace std;
class newType{
private:
int *p;
public:
newType();
~newType();
int fun(int n);
};
newType::newType(void) {
int n ;
p = new (nothrow) int[10];
if (p == NULL){
cout << "Error: memory could not be allocated";
}else{
for (n=0; n< 10; n++)
{
p[n] = rand() % 20 + 1;
}
cout << "Array Holding following elements: ";
for (n=0; n< 10 ; n++)
cout << p[n] << ",";
}
}
newType::~newType(){
delete[] p;
}
int newType::fun( int number ) {
int n = 0;
double product = 1;
cout << "Function Value " << number << endl;
for (; n< 10 ; n++){
if(p[n]%2 == 1 || p[n] > number ){
product = product * p[n];
//cout << product << endl;
}
}
return product;
}
int main ()
{
newType newTypeObj;
int num = newTypeObj.fun(18);
cout << "Product value : " << num << endl;
return 0;
}
description:
As mentioned newType class is defined in above code with three functions ( Constructor, destructor and fun )
Please check the output of the follwoing program and let me know we you face any difficulties to make understanding on above code.
output
------------
sh-4.2$ main
Array Holding following elements:
4,7,18,16,14,16,7,13,10,2,Function Value 18
Product value : 637
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.