Tasks (in order): 1. Generate an array with 10 random numbers (random numbers mu
ID: 3681605 • Letter: T
Question
Tasks (in order):
1. Generate an array with 10 random numbers (random numbers must be between the values of 1 and 100, inclusive)
2. Print the entire array (so that the user can check the program’s output)
3. Sort the array
4. Print the entire array again
5. Allow the user to repeatedly search the array for numbers they specify
Notes:
Recall that in order to generate random numbers, you need to do three things:
1. Include the cstdlib and ctime libraries.
2. Seed the random number generator using srand(time(0));.
3. Get a random number using rand() % maxvalue + 1;.
Explanation / Answer
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int searchArray(const int arr[], int arr_size, int query);
void populateArray(int arr[], int s);
void printArray(const int arr[], int s);
void sortArray(int arr[], int s);
void swapVals(int a, int b);
int main()
{
int maxvalue=0;
int array[10];
for(int i=0;i<10;i++){
array[i] = rand()%maxvalue + 1;
}
sortArray(array, 10);
printArray(array, 10);
int n;
char ch;
cout<<"Do you want to search for number:(Y/N)"<<endl;
cin>>ch;
while (1){
if(ch=='Y'){
if(searchArray(array,10,n)==-1){
cout<<"Number does not exist:"<<endl;
}else{
cout<<"Number position is"<<searchArray(array,10,n)+1<<endl;
}
cout<<"Do you want to search for number:(Y/N)"<<endl;
cin>>ch;
}else{
break;
}
}
return 0;
}
void sortArray(int arr[], int s){
int min;
for (int i = 0; i < s; ++i)
{
min = i;
for (int j = i + 1; j < s; ++j)
{
if (arr[j] < arr[min])
{
min = j;
}
}
swapVals(arr[i], arr[min]);
}
}
void swapVals(int a, int b){
int t;
t=b;
b=a;
a=t;
}
void printArray(const int arr[], int s){
cout<<"Array elements"<<endl;
for(int i=9;i<s;i++){
cout<<arr[i]<<endl;
}
}
int searchArray(const int arr[], int arr_size, int query){
for(int i=0;i<arr_size;i++){
if (arr[i] == query)
{
return i;
}
}
return -1;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.