Prime numbers 2

Here is my code that doesn`t compile. The task was to take an input value max and then find all prime numbers from 1 to max.

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
#include <vector>
#include <iostream>

using namespace std;

vector<int>prime;

bool is_prime(int n)
{
	for (int p = 0; p<prime.size(); ++p)
		if (n%prime[p]==0) return false;	// no remainder: prime[p] divided
	return true;	// no smaller prime could divide
}


int main()

{

cout << " Enter a max value "; '\n'


for (int max; cin>>max;)
   prime.push_back(max);
for (int i=0; i<=prime.size(); ++i)
    if (is_prime(max)) prime.push_back(max);	// add new prime to vector

cout << "Primes: ";
	for (int p = 0; p<prime.size(); ++p)
		cout << prime[p] << '\n';

  
}



Hope someone can spot the errors.
There was a bit of confusion but now it should be ok:

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
#include <vector>
#include <iostream>

using namespace std;

vector<int> prime;

bool is_prime(int n) {
	for (unsigned int p = 0; p < prime.size(); ++p) {
		if (n % prime[p] == 0)
			return false;	// no remainder: prime[p] divided
	}
	return true;	// no smaller prime could divide
}

int main() {
	int max;
	cout << " Enter a max value ";
	cin >> max;

	for (int i = 2; i <= max; ++i) {
		if (is_prime(i))
			prime.push_back(i);	// add new prime to vector
	}

	cout << "Primes: ";
	for (unsigned int p = 0; p < prime.size(); ++p)
		cout << prime[p] << '\n';
}
Line 20 is defective. The ; terminates the statement. the '\n' by itself does nothing and you missing both a << operator and a ; at the end.

line 23-24: Why are you looping here? You're getting multiple values of max and pushing them onto the vector without determining whether they are prime or not.

Line 25-26: If I enter one value, prime.size() is 1 and the loop will execute once.

Line 26: max is out of scope. max is only defined for the duration of the for loop at lines 23-24.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main()
{	int max; 

	cout << " Enter a max value " << '\n';
	cin>>max;
	for (int i=2; i<=max; ++i)
		if (is_prime(i)) 
			prime.push_back(i);	// add new prime to vector

	cout << "Primes: ";
	for (int p = 0; p<prime.size(); ++p)
		cout << prime[p] << '\n'; 
	system ("pause");
}



Ok. Thanks. I`m just thinking that how many exercises should I do per chapter, I`m on chapter 4 and usually

do something like 6/21. I do a self study.

I find most of the exercies boring.
> how many exercises should I do per chapter

There is not a "magic number"... Do some exercises until you feel you have learnt something and then move on. Probably you will have to re-look at many things but this is natural...
how many exercises should I do per chapter

Due to the mistakes above, I would suggest you're not doing enough.

Topic archived. No new replies allowed.