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.
#include<iostream>
usingnamespace 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.