Write a C++ program that: unsigned * smallValues(unsigned & all, unsigned & used
ID: 3737521 • Letter: W
Question
Write a C++ program that:
unsigned * smallValues(unsigned & all, unsigned & used,
unsigned f(unsigned n), unsigned threshold
if a is the returned DA array, smallValues sets
a[0] to f(0)
a[1] to f(1)
a[2] to f(2)
...
for as long as f(i) < threshold
e.g.
unsigned square(unsigned n) {return n*n;}
smallValues(all, used, square, 100)
smallValues returns {0, 1, 4, 9, 16, 25, 36, 49, 64, 81}
unsigned f0(unsigned n) {return 1000000;}
smallValues(all, used, f0, 10)
smallValues returns {}
smallValues returns a DA array to main
main outputs the (used) values, then main deallocate the array
if part of smallValues job were to output f(0), f(1), and f(2),
then
if main says
unsigned all, used;
unsigned * ptr = smallValues(all, used, square, 10);
show(ptr, used);
and if smallValues says
unsigned * smallValues(unsigned & all, unsigned & used,
unsigned f(unsigned n), unsigned threshold
){
cout <<"0 --> " <<f(0) <<endl;
cout <<"1 --> " <<f(1) <<endl;
cout <<"2 --> " <<f(2) <<endl;
...
smallValues initial allocation is 0 elements, and reallocates
according to
newAll = oldAlloc + oldAlloc/2 + 1
Explanation / Answer
Given below is the code for the question.
Please do rate the answer if it was helpful. Thank you
#include <iostream>
using namespace std;
unsigned * smallValues(unsigned & all, unsigned & used,
unsigned f(unsigned n), unsigned threshold);
void show(unsigned *ptr, int used);
unsigned square(unsigned n) {return n*n;}
unsigned f0(unsigned n) {return 1000000;}
int main()
{
unsigned all, used;
unsigned *ptr;
ptr = smallValues(all, used, square, 100);
cout << "using square() function, the values returned from smallValues() are ";
show(ptr, used);
delete[]ptr;
ptr = smallValues(all, used, f0, 100);
cout << "using f0() function, the values returned from smallValues() are ";
show(ptr, used);
delete[]ptr;
return 0;
}
unsigned * smallValues(unsigned & all, unsigned & used,
unsigned f(unsigned n), unsigned threshold)
{
unsigned *ptr = NULL;
all = 0;
used = 0;
for(int i = 0; f(i) < threshold; i++)
{
if(used == all) //if all allocated space is used, reallocate
{
///allocate temporary array and copy the values
all = all + all/2 + 1;
unsigned *temp = new unsigned[all];
for(int j = 0; j < used; j++)
temp[j] = ptr[j];
if(ptr != NULL) //deallocate old array
delete[] ptr;
ptr = temp;
}
ptr[i] = f(i);
used++;
}
return ptr;
}
void show(unsigned *ptr, int used)
{
cout << "{";
if(used > 0)
{
cout << ptr[0];
for(int i = 1; i <used; i++)
cout << ", " << ptr[i];
}
cout << "}" << endl;
}
output
=======
using square() function, the values returned from smallValues() are {0, 1, 4, 9, 16, 25, 36, 49, 64, 81}
using f0() function, the values returned from smallValues() are {}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.