This should be a C++ program. Write a program that can read a list of numbers, f
ID: 3858169 • Letter: T
Question
This should be a C++ program. Write a program that can read a list of numbers, find their average, sort the numbers, and search the average. The detailed tasks are described below. 1) Write a function named EvenOrOdd, which inspects the argument and returns an integer value. If the argument is even, the function returns 0; if odd, returns 1. 2) Write a function named ArrayAverage, which returns the average of an array. 3) Read 6 integers from the user’s input and store them in an array named numbers. Display the array elements (in the original order). 4) Declare an integer variable named avg. Call the function ArrayAverage to compute the average of the elements in the array numbers, and assign it to avg. 5) If avg is even, do the bubble sorting; if odd, do the selection sorting. In both cases, sort the array to an ascending order. Display the sorted array elements on the screen. 6) Apply the binary searching to find whether avg is in the array numbers. Display the searching result on the screen.
Explanation / Answer
///// Below is the C++ program
#include <iostream>
using namespace std;
int EvenOrOdd(int num){
if(num%2==0){
return 0;
}
return 1;
}
int ArrayAverage(int arr[],int len){
int avg=0;
for(int i=0;i<len;i++){
avg+= arr[i];
}
avg= avg/len;
return avg;
}
void bubblesort(int arr[],int n){
for(int i=0;i<n-1;i++){
for(int j=1;j<n-i-1;j++){
if(arr[j-1]>arr[j]){
int temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
}
}
}
}
void selectionsort(int arr[], int n){
for(int i=0;i<n;i++){
int min = 2147483647;
int index = i;
for(int j=i;j<n;j++){
if(arr[j]<min){
min = arr[j];
index = j;
}
}
int temp = arr[index];
arr[index] = arr[i];
arr[i] = temp;
}
}
void binarySearch(int arr[], int num, int len){
int mid;
int start = 0;
int end = len-1;
while(start<end){
mid = (start+end)/2;
if(arr[mid]==num){
cout<<"Yes"<<endl;
return;
}
else if(arr[mid]<num){
start=mid+1;
}
else{
end=mid;
}
}
cout<<"No"<<endl;
}
int main(int argc, char** argv) {
int numbers[6];
int inp;
for(int i=0;i<6;i++){
cin>>inp;
numbers[i]=inp;
}
cout<<"Numbers are: ";
for(int i=0;i<6;i++){
cout<<numbers[i]<<" ";
}
cout<<endl;
int avg = ArrayAverage(numbers,6);
cout<<"Average is: "<<avg<<endl;
if(EvenOrOdd(avg)==0){
bubblesort(numbers,6);
}
else{
selectionsort(numbers,6);
}
cout<<"Sorted array: ";
for(int i=0;i<6;i++){
cout<<numbers[i]<<" ";
}
cout<<endl;
cout<<"Avg number in array? --> ";
binarySearch(numbers,avg,6);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.