First, write a program to create an array and it up with 20 randomly gencrated i
ID: 3880655 • Letter: F
Question
First, write a program to create an array and it up with 20 randomly gencrated integers (range 0-10) and output the array. (Hint: Check the provided PowerPoint file regarding the random number generator code.) Part 1 Write a function to implement following function prototype: void search(int array[l, int length, int key); The function takes input an integer array, the size of the array, and a key to search. The function outputs the key value and a message whether the key exists in the array or not. If the key exists function outputs the number of occurrence of the key in the array Part 2: Write a function to sort the array in Descending order (from largest to smallest) and output the result. You should implement the following function prototype and use the sclection sort provided in the text book. void selectionSort (int list[], int length); Sub a single cpp file for both questions. You should get the similar output as below Output: CAWINDOWS system32cmd.exe 0 0 has found nunber of oc urrence is 4 0 not Found ress any key to continue .Explanation / Answer
#include<iostream>
#include<cstdlib>
using namespace std;
void search(int array[],int n,int key)//method seach key in a
{
int i;
int c=0;
for(i=0;i<n;i++)
{
if(array[i]==key)c++;//if found increamentin count
}
if(c>0)
{
cout<<key<<" found "<<c<<" times in array ";
}
else
{
cout<<key<<"not found"<<endl;
}
}
void print_array(int a[],int n)//method to print array
{
int i;
cout<<"your array: ";
for(i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<endl;
}
void selectionSort(int list[],int length)//method to sort array in descending order
{
int i,j,max=0,k,n=length;
for(i=0;i<n-1;i++)
{
for(j=i;j<n;j++)
{
if(list[j]>list[max])
{
max=j;
}
}
k=list[i];
list[i]=list[max];
list[max]=k;
}
}
int main()
{
int a[20];//creating array
int i;
for(i=0;i<10;i++)//assigning random numbers ot array
{
a[i]=rand()%10;//generating random number
}
print_array(a,20);
cout<<" Enter value to seach:";
int k;
cin>>k;
search(a,20,k);
selectionSort(a,20);
print_array(a,20);
return 0;
}
output:
your array: 1 7 4 0 9 4 8 8 2 4 4232341 0 1 0 4228393 0 0 0 40 0
Enter value to seach:1
1 found 2 times in array
your array: 4232341 4228393 40 9 8 8 7 2 4 1 4 4 0 1 0 0 0 0 0 0
Process exited normally.
Press any key to continue . . .
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.