26,544 views
33 votes
33 votes
Write an algorithm to print even numbers from 1 to 100

User Matti VM
by
3.0k points

1 Answer

17 votes
17 votes

Answer:

// Java solution

for ( int i = 0; i < 101; i++)

{

if ( i % 2 == 0)

{

System.out.println( i + " ");

}

}

Using modulus, whatever number we are currently on in our loop is evaluated to see if it is even. Any number divided by 2 that is even will not have a remainder, hence ==0. So we just print the numbers that satisfy that condition and we have all evens.

User Ryanc
by
2.7k points