I am currently doing an intro C++ assignment and ran into some confusion. The code is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
int n = 0;
int i = 2;
bool primenumber = true;
cout << "Enter a number and press ENTER: " << endl;
cin >> n;
while (i <= sqrt(n)) { if (n%i == 0) {primenumber = false; } ++i; }
if (primenumber) { cout << "Number is prime." << endl; }
else { cout << "Number is not prime." << endl; }
return 0;
I understood all of it except one thing: "++i"
Why do we add one to "i"? I noticed when I took it out, the program would not print "Number is not prime." for non prime numbers. I thought about it for a while but still couldn't grasp its significance.
If someone could point me in the right direction it would be really helpful.
n being the number that is checked if it's prime or not.
The reason you increase i is because you divide n by i and check the remainder. By doing this you check if n has any factors or is divisible (if it is it's not prime and it has a remainder of 0). If all the divisions (i increases) come out as not 0 then it is prime.