Please help edit the following program so that the user can input their own arra
ID: 3607119 • Letter: P
Question
Please help edit the following program so that the user can input their own array of numbers that are then searched for particular number indexes.
#include "stdafx.h"
#include<iostream>
#include<stdlib.h>
using namespace std;
void randomArray(int *arr, int length);
int linear(int arr[], int length, int key);
int main() {
int arr[100], ind, key, i;
cout << "The random array is:" << endl;
randomArray(arr, 100);
for (i = 0;i < 100;i++)
cout << arr[i] << " ";
cout << endl;
cout << "Please enter a number to search for:" << endl;
cin >> key;
ind = linear(arr, 100, key);
if (ind == -1)
{
cout << "The key is not in the given random array." << endl;
system("pause");
}
else
cout << "The key is at index: " << ind << endl;
system("pause");
return 0;
}
void randomArray(int *arr, int length) {
int i;
for (i = 0;i<length;i++) {
*(arr + i) = rand() % 150;
}
}
int linear(int arr[], int length, int key) {
if (length - 1 != -1) {
if (arr[length - 1] == key)
return length - 1;
else
return linear(arr, length - 1, key);
system("pause");
}
else
return -1;
system("pause");
}
Explanation / Answer
//Here is the new program that can take input array of numbers instead of generating random numbers in array from user
#include<iostream>
#include<stdlib.h>
using namespace std;
void inputArray(int *arr, int length);
int linear(int arr[], int length, int key);
int main() {
int arr[100], ind, key, i;
cout << "The input array is:" << endl;
inputArray(arr, 100);
for (i = 0;i < 100;i++)
cout << arr[i] << " ";
cout << endl;
cout << "Please enter a number to search for:" << endl;
cin >> key;
ind = linear(arr, 100, key);
if (ind == -1)
{
cout << "The key is not in the given random array." << endl;
system("pause");
}
else
cout << "The key is at index: " << ind << endl;
system("pause");
return 0;
}
//used to ask user input of array of numbers
void inputArray(int *arr, int length) {
int i;
for (i = 0;i<length;i++) {
cout<<"Enter the number:";
cin>> *(arr + i);
}
}
int linear(int arr[], int length, int key) {
if (length - 1 != -1) {
if (arr[length - 1] == key)
return length - 1;
else
return linear(arr, length - 1, key);
}
return -1;
system("pause");
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.