In: Computer Science
Using Pass-by-Reference for Out Parameters Write a single function that counts the number of positive, negative and zero values in an integer array. Return the number of positive values, the number of negative values and the number of zero values. Use pass-by-reference to use parameters as “out parameter”: these are variables passed by reference into a function with the purpose of holding the result of the function after it terminates. Your function should have the following declaration: void countPosNegZero(int array[], int numElements, int &positive, int &negative, int &zero); where array is the array with the values, numElements is the number of elements in the array, positive will hold the number of positive values in the array, negative will hold the number of negative values in the array and zero will hold the number of zero values in the array. Add a test-main function that tests your program with several different arrays (use the rand() method to create arrays with random values ranging over negative and positive values).
c++
Hi,
Please find the code below and output attached.
#include<iostream>
using namespace std;
#include <ctime> // this is required to use rand function
//the out parameter will be of type out&, i.e passed by
reference,it means value that is passed can be modified by the
function
// when we pass by reference values modified will also be visible
in the main function here.
void countPosNegZero(int array[], int numElements, int
&positive, int &negative, int &zero)
{
for(int i=0; i<numElements; i++)
{
if(array[i]<0)
{
negative++;
}
else if(array[i]==0)
{
zero++;
}
else
{
positive++;
}
}
}
int main()
{
int countp=0, countn=0, countz=0, arr[10], i;
int numOfElements;
int secondArray[50];
cout << "Please enter the number of elements"
<< endl;
cin >> numOfElements;
cout << "Now enter "<< numOfElements
<< "integers" << endl;
for(i=0; i<numOfElements; i++)
{
cin>>arr[i];
}
countPosNegZero(arr,numOfElements,countp,countn,countz);
cout << "Positive Integers count:" <<
countp << endl;
cout << "Negative integers count:" <<
countn << endl;
cout << "No of zeros:" << countz <<
endl;
// this is using rand to generate random array of 50
integers.
srand(time(0));
for(int i=0; i<50; i++)
{
secondArray[i] = rand()%100-20; // -20 just to generate negative
numbers also
cout << secondArray[i] << "\t";
}
countp=0, countn=0, countz=0; // initializing them again t 0 to
reuse
countPosNegZero(secondArray,50,countp,countn,countz);
cout << "Positive Integers count using rand :"
<< countp << endl;
cout << "Negative integers count using rand:"
<< countn << endl;
cout << "No of zeros using rand:" <<
countz << endl;
return 0;
}
thanks,
kindly upvote.