Task 2: Number of Occurrences
Task
Write a program using a vector to perform the following:
- Read integer values from standard input and insert them in a vector until a negative integer is encountered;
- Read an extra non-negative integer n;
- Output the number of occurrences of n encountered during phase (1).
Your solution must split the sub-tasks of the program (reading the vector, counting the occurrences, and maybe other sub-tasks) into separate functions. Those functions must use the proper reference parameters to access the vector.
Note: we consider solutions as incorrect if they use library functions (or data structures) beyond the ones discussed in the lectures so far to perform the actual computation.
Input
A sequence of of integer values containing a single negative integer, in penultimate position.
Example:
0 1 1 2 3 5 8 13 21 -1 1
Output
The number of occurrences of the last integer in the sequence before the negative integer.
Example: for the input given above, the number of occurrences of 1 before -1 occurs is
2
Reminder - How to use vector
To define a vector (for example of integer numbers), you can use the following constructor
std::vector<int> my vec = std::vector<int>(length, init_value);
You can insert element at the back of the vector with:
my_vec.push_back(number);
To access the elements of the vector you have to use the random access ([]) operator:
std::cout << "First element: " << my_vec[0];
Solution
#include <iostream>
#include <vector>
void readvec(std::vector<int>& vec, int& num) {
vec.push_back(num);
}
int occvec(std::vector<int>& vec, int& num, int& count) {
for (unsigned long i = 0; i < vec.size(); ++i) {
if (vec[i] == num)
++count;
}
return count;
}
int main() {
int i;
int con;
int count = 0;
std::vector<int> vec;
std::cin >> i;
while (i >= 0) {
readvec(vec, i);
std::cin >> i;
}
std::cin >> con;
occvec(vec, con, count);
std::cout << count;
return 0;
}
Made by JirR02 in Switzerland 🇨🇭