For loop and while loop



both of these code are basic prime check one with while loop and another is with for loop. If both for and while loop gives same answer then why my code with for loop is giving error

@ikrarrus
Two syntax errors in your code with for loop.

  1. Declare i before the for loop and not in it.
    int i = 2;
    for(i ; i<N; i++)

  2. Remove the extra semicolon in Line 16 after the inverted commas.

So yes it worked , But if I initialize int i outside the loop and also do the same in for loop e.g.
int i = 2;
for(int i =2 ; i<N; i++)
will my code work if not why?

@ikrarrus
This won’t work. The i initialised before loop has value 2 and it will remain two throughout the code and never change. The i declared in the loop is a seperate variable and will get incremented through the loop. Your final condition after the loop is i==n. This compares the i declared before the loop which had value 2 as a constant and never changed. Hence this condition will always fail except when n = 2.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.