How would you go about populate a array with random value then pass the array and its length to the function. (example)
The array size is 6 it contains {-12,35,5,22.1,65,-9} it should return all positive value less than 40.
1 2 3 4 5 6 7 8 9 10
double addValue(constdouble array1[], int number)
{
int sum = 0;
for(int i=0;i<length;i++){
if(array1[i] < 40 && array1[i] > 0){
sum = sum + array[i];
}
}
return sum;
}
You can not return "all positive numbers" because function can return only one object.
You could return a vector of all positive numbers. For example
1 2 3 4 5 6 7 8 9 10 11
std::vector<double> positiveNumbers( double a[], int size, double value )
{
std::vector<double> v;
for ( int i = 0; i < size; i++ )
{
if ( 0 < a[i] && a[i] < value ) v.push_back( a[i] );
}
return ( v );
}
If you have to do the same without the vector you should use a pointer to an allocated array
double * positiveNumbers( double a[], int size, double value )
{
int count = 0;
double *p = 0;
for ( int i = 0; i < size; i++ )
{
if ( 0 < a[i] && a[i] < value ) ++count;
}
if ( count != 0 )
{
p = newdouble[count];
for ( int i = 0, j = 0; i < size; i++ )
{
if ( 0 < a[i] && a[i] < value ) p[j++] = a[i];
}
}
return ( p );
}
By the way you could use standard algorithm std::copy_if
The first value in an array created and returned like that should be the length of the array (such method would also protect against count ending up as zero).
you know when you populate an array do you have to create a new array
example double array2 [3] = { }; or no who can use one array and generate random number into the array?
You'd probably want to create a new one to be populated.
Though, Vlad's idea is the best; use a vector.
What happens if you create an array of three elements and you find four values that are less than 40? Because you're array is only three elements in size, you're going to lose that fourth value.
There are ways to dynamically size the array, sure, but the most obvious and simple solution is the vector class.