Finding Prime No.s

I am new to programming using c++ and I want to make a program that prints the first N prime nos.when I debug it doesnt give me the desired output for example I input 5 it gives me :2 3 4 5 6 whats my mistake?

here's my code:
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
#include <iostream>
using namespace std;

int main(){
	int N;
	cin >> N;
	for(int i=2;N>0;++i)
	{
		bool IsPrime=true;
		for(int j=2;j<i;++j)
		{
		if(i % j == 0)
		{
			bool IsPrime=false;
		break;
		}
		}
		if(IsPrime)
		{
			--N;
			cout << i << "\n";
		}
	}
	return 0;
}
Last edited on
Notice bool on line 14. It makes so that you are defining a new variable that is local to that if statement and is not the same variable as you defined on line 9 so that's why it remains unchanged.
Thanks that was the problem .. But I don't understand how the for loop and the nested one work to identify the prime no.s then display them ??
Did you not write the program?
no I just copied the solution .. I wasn't able to write it on my own
Perhaps you should read some introductory material, for example the http://www.cplusplus.com/doc/tutorial/
in order to learn at least some of the basics first.
Topic archived. No new replies allowed.