In: Computer Science
In C++ Write a function that accepts two int arrays of the same size. The first array will contain numbers and the second array will be filled out inside the function. THE FUNCTION SHOULD FIND ALL NUMBERS IN THE ARRAY THAT ARE GREATER THAN OR EQUAL TO THE AVERAGE. You need to design the function. so the output code should be:
(show contents of 1st array)
The numbers that are greater than the average of the first array are: (the numbers)
so if the array is 1 2 3 4 5 . The numbers outputted should be 3 4 and 5 because 15/5=3 and 3 4 and are greater than and equal to 3.
I tried this code but the errors returned were: expression must have a constant value #include using namespace std; void fillArray(int arr1[],int arr2[],int arr_size) { int cnt=0; double avg,sum; for(int i=0;i=avg)//condition to check average { arr2[cnt]=arr1[i]; //assigning value to array 2 cnt++; } } //printing seond array cout<<"Second array is: "; for(int i=0;i>arr_size; int arr1[arr_size],arr2[arr_size]; cout<<"Enter the element:\n"; for(int i=0;i>arr1[i]; } fillArray(arr1,arr2,arr_size); }
also this code is incomplete:
#include <iostrecam>
using namespace std;
// function declaration
void fun(int arr1[], int arr2[], int size){
cout<<"Content of 1st array:
"<<endl;
for(int i=0; i<size; i++)
cout<<arr1[i]<<"
";
cout<<endl;
// taking input for 2nd array from user
cout<<"\nEnter "<<size<<" integers
:"<<endl;
for(int i=0; i<size; i++)
cin>>arr2[i];
cout<<"\nContent of 2st array:
"<<endl;
for(int i=0; i<size; i++)
cout<<arr2[i]<<"
";
cout<<endl;
}
int main(){
// declaring two array of size 6 and initializing
first array with some value
int arr1[] = {1,2,3,4,5,6};
int arr2[6];
// calling function
fun(arr1, arr2, 6);
return 0;
}
Code: I modifies your code to get correct output
#include <iostream>
using namespace std;
// function declaration
void fun(int arr1[], int arr2[], int size){
double sum=0,avrg;
cout<<"Content of 1st array: "<<endl;
for(int i=0; i<size; i++)
{
cout<<arr1[i]<<" ";
sum=sum+arr1[i];//caluclating Sum;
}
cout<<endl;
avrg=sum/size;//caluclating Average
int count=0;
//Storing values to array2 if its greater than average
for(int i=0;i<size;i++){
if(arr1[i]>=avrg){
arr2[count]=arr1[i];
count++;}
}
cout<<"\nContent of 2st array: "<<endl;
for(int i=0; i<count; i++)
cout<<arr2[i]<<" ";
cout<<endl;
}
int main(){
// declaring two array of size 6 and initializing first array
with some value
int arr1[] = {1,2,3,4,5};
int arr2[5];
// calling function
fun(arr1, arr2, 5);
return 0;
}
Output:
*Feel free to ask(comment) if you have any doubts or if you face any difficulties while executing the program, I will be happy to help you, please upvote if you like the solution