generate vectors with even numbers

I need to write a function that creates and returns an int vector with even numbers, starting with 2. Here is what I have so far:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <vector>
#include <iostream>
using namespace std;

//forward declarations
vector<int> getEvenNumbers(int n);
void printVector(const vector<int> & v);

int main()
{	vector<int> v = getEvenNumbers(10); //even numbers from 2 to 20
	printVector(v);
	cout << endl;
	return 0;
}

//function to generate even numbers
vector<int> getEvenNumbers(int n)
{	vector<int> v(n);
	while (v[n] % 2 == 0) //to make sure the # is even
	{
		v.push_back(n);
	}
	return v;
}

//Function to print a (small) vector of integers
void printVector(const vector<int> & v){
	cout << "{";
	for (int i = 0; i < v.size(); ++i){
		cout << v[i];
		if(i < v.size() - 1){
			cout << ",";
		}	
	}
	cout << "}";
}


My code is all over the place and doesn't even make sense, and it doesn't run because I think my function to generate even numbers is all wrong, but i have no idea how to fix it, any hints would be awesome!
In your getEvenNumbers function, you aren't changing n or checking to see if you've produced enough numbers, making it go into an infinite loop.
Do you need to determine even numbers in a given range or generate a specified number of even numbers?


For each number i from 2 to 20:
is i even

---or---

For each number i from 1 to 10:
n = i * 2

Now, would you really need to test that n is even?
Last edited on
Topic archived. No new replies allowed.