2. When we want to intialize a dynamically allocated float array we may choose o
ID: 3561958 • Letter: 2
Question
2. When we want to intialize a dynamically allocated float array we may choose one of the following methods: The array size is not specified so it is intialized to 1 and the values stored in the array is set to 0.0. The array is allocated to a specified size but the values stored in the array are not specified In this case, all the values in the array are set to 0.0 The array is allocated to a specified size and the values stored in the array are all set to a specified value. Write the three versions of the init() function in the following program: File intializearray.cpp This program uses a number of different functions to initialize an array Programmer: your name Date #include Kiostream #includeExplanation / Answer
#include <iostream>
using namespace std;
float * init (void);
float * init (int n);
float * init (int n, float val);
int main ()
{
float *x;
float val;
int n;
int i;
n = 1;
x = init();
cout << " x = ";
for (i = 0; i < n; i++)
{
cout << x[i] << endl;
}
n = 4;
x = init (n);
cout << " x = ";
for (i = 0; i < n; i++)
{
cout << x[i] << endl;
}
delete [] x;
n = 5;
val = 1.27;
x = init (n, val);
cout << " x = ";
for (i = 0; i < n; i++)
{
cout << x[i] << endl;
}
delete [] x;
return 0;
}
float * init (void)
{
float x = 0.0;
float *array = &x;
return (array);
}
float * init (int n)
{
float *array = 0;
int i;
array = new float [n];
for (i = 0; i < n; i++)
{
array[i] = 0.0;
}
return (array);
}
float * init (int n, float val)
{
float *array = 0;
int i;
array = new float [n];
for (i = 0; i < n; i++)
{
array[i] = val;
}
return (array);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.