Write a C++ program in which you create an array with 250 elements. Populate the
ID: 646898 • Letter: W
Question
Write a C++ program in which you create an array with 250 elements. Populate the array with random real numbers between 1 and 100. Using the statistics library, calculate and output the following values: maximum, minimum, mean, standard deviation, and variance. Next, sort the array and output the median value. Finally, ask the user to enter a value that he/she would like to search for. Return the result using both the linear search and the binary search, where the result is the index of the first instance of the value that is found or -1 if the value doesn't exist in the array. If a value in the array is within +/- 1% of the search value, consider the value to be found. Add the sort and search functions to your statistics library.
Explanation / Answer
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
int main ()
{
int A[250],i,small,large;
srand((unsigned)time(0));
for(int i=0; i<size; i++){
A[i] = (rand()%100)+1;
cout << A[i] << endl;
}
small=A[0];
large=A[0];
for(i=1;i<n;i++)
{
if(A[i]<small)
small=A[i];
if(A[i]>large)
large=A[i];
}
cout<<" Largest element is :"<<large;
cout<<" Smallest element is :"<<small;
for (i=0; i<n-1; i++)
for (j=i+1; j<n; j++)
if (A[i]>A[j])
{
temp=A[i];
A[i]=A[j];
A[j]=temp;
}
printf("The sorted array looks like this: ");
for (i=0; i<n; i++)
printf("A[%d]=%d ", i, A[i]);
}
int searching_element=0;
int flag=0;
cout<<" Enter the element you want to find = ";
cin>>searching_element;
flag=linear_search(A,100,searching_element);
if(flag!=-1)
cout<<" The given element is found at the position A["<<
flag<<"]"<<endl;
else
cout<<" The given element is not found. "<<endl;
}
int linear_search(int array[],int size,int element)
{
for(int count=0;count<size;count++)
{
if(element==array[count])
{
return count;
}
}
return -1;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.