Confusion

Can someone explain how this works? step by step and the flow control of the for loops, I've not learnt much about nested loops, thank you.
I usualy like to go over the flow control of a program in my text book so I can fully understand it, but this one is confusing me since I don't know about nested for loops (I think that's the problem) anyway.

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 num;
	bool prime;
	a:
	cout << "Please enter a positive integer" << endl;
	cin >> num;

	for (int i = 2; i <= num; i++){
		prime = true;
		for (int n = 2; n <= i - 1;n++){
			if (i % n  == 0){
				prime = false;
			}
		}
		if (prime){
			cout << i << " is prime" << endl;
		}
		
	}
	goto a;
return 0;
}
I'm not sure exactly what you're confused by, but when working out the flow of a program, treat each loop individually, and only advance past the closing curly brace when the loop is finished. That means that on each iteration of the outer loop, the inner loop loops as many times as it can.

Also, I'd advise using a while loop instead of goto and use prefix increment instead of postfix.
I'm such an idiot, I didnt see the -1 on the second for loop:( omg
Face palm
Topic archived. No new replies allowed.