# What's wrong with my loop

closed Sep 28
I'm trying to write a loop that prints even numbers
from 1 to 20, what am I doing wrong?

int i, rem;

for(i=1;i<21;i++);
{
rem=i%2;
if(rem=0)
printf("%d\n", i);
}

answered Sep 26 by (140 points)
int i, rem;

for(i=1;i<21;i++) //no need of ; here
{
rem=i%2;
if(rem==0) // use "==" for checking value
printf("%d\n", i);
}
answered Sep 26 by (140 points)
do not use ";" in the end of the  for loop line.

condition need double "=" so, if(rem==0).
answered Sep 26 by (140 points)
#include <stdio.h>

int main()
{
int i, rem;

for(i=2;i<+21;i++)
{
rem=i%2;
if(rem==0)
{
printf("%d\n",i);
}
}
return 0;
}
answered Sep 26 by (140 points)
#include <stdio.h>

int main() {

int counter;

printf("Even numbers between 1 to 20\n");

for(counter = 1; counter <= 20; counter++) {

/* Even numbers are divisible by 2 */

if(counter%2 == 0) {

/* counter is even, print it */

printf("%d ", counter);

}

}

return 0;

}
commented 2 days ago by (140 points)
Can you please explain it using while loop ?
answered Sep 26 by (34,450 points)

Others have already told you that you must remove the semicolon from the end of the for and to compare numbers you need to use ==.

Here, I'd like to show an alternative solution, keeping performance in mind.

The idea is that instead of testing every single number if it is even, we could just find the first even number and then just jump to the next even number (increment by 2).

If start is even, it's the first even number. If it is odd, then start + 1 is the first even number.

```#include <stdio.h>

// Print even numbers between start and end inclusive, one number a line.
void PrintEvenNumbers(int start, int end)
{
for (int i = (start % 2 == 0 ? start : start + 1); i <= end; i += 2)
printf("%d\n", i);
}

void main()
{
PrintEvenNumbers(1, 21);
}```
answered Sep 27 by (140 points)

wrong operator being used!

you are using assingnment operator "=" instead of relational operator "==".

our purpose is to check a condition , for which we have to use relational operator equal to(==) !

while using = will assign rem as zero each time.

commented 2 days ago by (140 points)
He has aslo added ; after for loop. That too might be giving error.
commented 1 day ago by (140 points)
No , look carefully that ; is after ternary operator expression not after for loop.