In: Computer Science
Write a statement to call prepare Arr to set values for the array (Using C++)
#include
using namespace std;
const int NUM = 10;
void prepareArr(int a[]);
int countEven (int b[]);
int main() {
int arr[NUM];
// write a statement to call prepareArr to set values for the
array
// write a statement to call countEven and print the data
returned
for(int i = 0; i cout << arr[i] <<" ";
cout <
return 0;
}
void prepareArr(int a[])
{
//randomly generate NUM integers in the range [0,99] and save them
in the array parameter.
}
int countEven (int b[])
{
//count the number of even integers in the array parameter and
return the number, note that the size of the array is specified
with NUM.
}
Answer in C++
Since here we're supposed to pass the array as an argument to the functions. I would like to tell you something about how arrays are passed as an argument in cpp. Unlike any other datatype variables, the entire array is not passed to the function, instead only the first element's address is passed.
Now, coming to your question. Here's the complete, commented code:
#include<iostream>
using namespace std;
const int NUM = 10;
void prepareArr(int a[]);
int countEven (int b[]);
int main()
{
int arr[NUM];
// write a statement to call prepareArr to set values for the array
prepareArr(arr); // as the return type of prepareArr() is void, nothing is returned to be stored into another variable.
// write a statement to call countEven and print the data returned
int evenCnt = countEven(arr); // as the return type is int, the value returned by the function has to be caught by some other int type variable.
cout << "Value returned by countEven() : " << evenCnt << endl; // printing the returned value
for(int i = 0; i<NUM; i++)
cout << arr[i] <<" ";
cout <<endl;
return 0;
}
void prepareArr(int a[])
{
//randomly generate NUM integers in the range [0,99] and save them in the array parameter.
int lower = 0, upper = 99;
for(int i = 0; i < NUM; i++)
a[i] = (rand() % (upper - lower + 1)) + lower; // this formula is used to set the range to generate random numbers between a given range.
}
int countEven (int b[])
{
//count the number of even integers in the array parameter and return the number, note that the size of the array is specified with NUM.
int cnt = 0; // variable to store the final answer
for(int i = 0; i < NUM; i++) // for traversing through the array
if(b[i]%2 == 0) // check for even number
cnt++; // if yes, then increment the variable.
return cnt; // returning the value.
}
Here's the screenshot of the code in my IDE for a better understanding of indentation:
And here's the screenshot of the output generated from this:
Although the code is heavily commented and everything is explained there itself, but in case you have a query do feel free to ask it out in the comments down below :)