171k views
2 votes
Write a for loop to populate vector userGuesses with NUM_GUESSES integers. Read integers using cin. Ex: If NUM_GUESSES is 3 and user enters 9 5 2, then userGuesses is {9, 5, 2}.

2 Answers

4 votes
#include <iostream>
#include <vector>

#define NUM_GUESSES 3

int main()
{
std::vector<int> userGuesses;
for (int i = 0, input; i < NUM_GUESSES; i++)
{
std::cin >> input;
userGuesses.push_back(input);
}
}
User BenoitVasseur
by
6.5k points
6 votes

Answer:

The solution code is written in C++.

  1. vector<int> userGuesses;
  2. int NUM_GUESSES = 3;
  3. int i;
  4. int inputNum;
  5. for(i = 1; i <= NUM_GUESSES; i++){
  6. cin>>inputNum;
  7. userGuesses.push_back(inputNum);
  8. }

Step-by-step explanation:

By presuming there is a vector, userGuesses and the NUM_GUESSES is 3 (Line 1 - 2).

Next we can create a for-loop that will run for NUM_GUESSES round of iterations. In each iteration, we use cin to get an input number and then use push_back method to add the input number to the userGuesses vector (Line 7 - 10).

User Cralfaro
by
7.3k points