In: Computer Science
Write two versions of a program that reads from the user a
sequence of positive integers ending with -1, and another positive
integer num that the
user wishes to search for.
The program should then print all the line numbers in sequence
entered by the user, that
contain num, or a message saying that num does not show at all in
the sequence.
Your program should interact with the user exactly as it shows in
the following example:
Please enter a sequence of positive integers, each in a separate
line.
End you input by typing -1.
13
5
8
2
9
5
8
8
-1
Please enter a number you want to search.
5
5 shows in lines 2, 6.
a) The first version of the program, is not allowed to use the
vector data structure.
b) The second version of the program, should use the vector data
structure.
Implementation requirements (for both programs):
1. Think how to break down your implementation to functions.
2. Your programs should run in linear time. That is, if there are n
numbers in the input
sequence, your program should run in ?(?).
3. Write the two programs in two functions named main1() and
main2(). Also have
the main() test these two functions.
If you have any doubts, please give me comment...
#include <iostream>
#include <vector>
using namespace std;
#define MAX_SIZE 50
void main1(int arr[], int n);
void main2(vector<int> vec);
int main()
{
int arr[MAX_SIZE], el, n;
vector<int> vec;
n = 0;
cout << "End you input by typing -1." << endl;
cin >> el;
while (el != -1)
{
arr[n] = el;
vec.push_back(el);
n++;
cin >> el;
}
main1(arr, n);
main2(vec);
return 0;
}
void main1(int arr[], int n)
{
cout << "Executing from main1: " << endl;
int i, search;
cout << "Please enter a number you want to search." << endl;
cin >> search;
bool isFirst = true;
for (i = 0; i < n; i++)
{
if (arr[i] == search)
{
if (isFirst)
{
cout << search << " shows in lines " << (i + 1);
isFirst = false;
}
else
cout << ", " << (i + 1);
}
}
if (isFirst)
cout << search << " not found" << endl;
else
cout << "." << endl;
}
void main2(vector<int> vec)
{
cout << "Executing from main2: " << endl;
int i, search;
cout << "Please enter a number you want to search." << endl;
cin >> search;
bool isFirst = true;
for (i = 0; i < vec.size(); i++)
{
if (vec.at(i) == search)
{
if (isFirst)
{
cout << search << " shows in lines " << (i + 1);
isFirst = false;
}
else
cout << ", " << (i + 1);
}
}
if (isFirst)
cout << search << " not found" << endl;
else
cout << "." << endl;
}