how to get the even numbers between 2 numbers using a loop

39 views (last 30 days)
ali b on 27 Jun 2015
So, for example, between 5 and 13 it would show: [6 8 10 12]
dpb on 27 Jun 2015
So what have you tried so far? We tend to not do homework (or what appears to be homework whether is or not) w/o the poster showing efforts made to date and asking a specific question. Just posting a solution helps neither party...

Star Strider on 27 Jun 2015
Edited: Star Strider on 27 Jun 2015
The easy way without a loop is:
first = 5;
second = 13;
v = first:second;
v_even = v(rem(v,2)==0)
With a loop, it’s a bit more complicated:
k2 = 1;
for k1 = first:second
if (rem(k1,2)==0)
v_even(k2) = k1;
k2 = k2 + 1;
end
end
Stephen on 13 Jul 2015
>> A = 5;
>> Z = 13;
>> A+rem(A,2):2:Z
ans =
6 8 10 12
This method generates a vector containing only the even numbers, which is much more efficient than generating a vector with all values and then keeping only the even values.

Rohan Yadav on 14 Oct 2021
k2 = 1;
for k1 = first:second
if (rem(k1,2)==0)
v_even(k2) = k1;
k2 = k2 + 1;
end
end