74.0k views
1 vote
Use a vector to solve the following problem. Read in 20 numbers, each of which is between 10 and 100, inclusive. As each number is read, validate it and store it in the vector only if it isn't a duplicate of a number already read. After reading all the values, display only the unique values that the user entered. Begin with an empty vector and use its push_back function to add each unique value to the vector.

User Roza
by
6.2k points

1 Answer

4 votes

Answer:

The following are the program in the C++ Programming Language.

//header files

#include <iostream>

#include <vector>

//using namespace

using namespace std;

//define a function

int find(vector<int> &vec, int n)

{

//set the for loop

for(int i = 0; i < vec.size(); ++i)

{

//check the elements of v is in the num

if(vec[i] == n)

{

//then, return the values of i

return i;

}

}

return -1;

}

//define the main method

int main()

{

//declare a integer vector type variable

vector<int> vec;

//print message

cout << "Enter numbers: ";

//declare integer type variable

int n;

//set the for loop

for(int i = 0; i < 20; ++i)

{

//get input in the 'num' from the user

cin >> n;

//check the following conditions

if(n >= 10 && n <= 100 && find(vec, n) == -1)

{

//then, assign the values of 'num' in the vector

vec.push_back(n);

}

}

//print the message

cout << "User entered: ";

//set the for loop

for(int i = 0; i < vec.size(); ++i)

{

//print the output

cout << vec[i] << " ";

}

cout << "\\";

return 0;

}

Output:

Enter numbers: 14 18 96 75 23 65 47 12 58 74 76 92 34 32 65 48 46 28 75 56

User entered: 14 18 96 75 23 65 47 12 58 74 76 92 34 32 48 46 28 56

Step-by-step explanation:

The following are the description of the program:

  • Firstly, set the required header files and required namespace.
  • Define an integer data type function 'find()' and pass two arguments that is integer vector type argument 'vec' and integer data type argument 'n'.
  • Then, set the for loop that iterates according to the size of the vector variable 'vec' inside the function, after that set the if conditional statement to check the following condition and return the variable 'i'.
  • Define the main method that gets the input from the user then, check that the following inputs are greater than 10 and smaller than 100 then assign these variables in the vector type variable 'vec' and print all the elements.
User Myro
by
7.3k points