Help

I need help understanding this code used to print N prime numbers :
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)
		{
			 IsPrime=false;
		break;
		}
		}
		if(IsPrime)
		{
			--N;
			cout << i << "\n";
		}
	}
	return 0;
}

how does the for loop and the nested for loop work to identify the prime numbers??

The indentation doesn't reflect the actual structure. Here is the code indented better:
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)
			{
				IsPrime=false;
				break;
			}
		}
		if(IsPrime)
		{
			--N;
			cout << i << "\n";
		}
	}
	return 0;
}

i is a candidate for a prime number. In other words, the code will determine whether i is prime. j is a possible factor of i. The 12 checks whether j divides i evenly (i.e., whether j is a factor of i). If it does then i is not prime so it sets IsPrime to false and breaks out of the loop (lines 14 & 15).
Topic archived. No new replies allowed.