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

24 views (last 30 days)
So, for example, between 5 and 13 it would show: [6 8 10 12]
  1 Comment
dpb
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...

Sign in to comment.

Accepted Answer

Star Strider
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
  1 Comment
Stephen23
Stephen23 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.

Sign in to comment.

More Answers (1)

Rohan Yadav
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

Categories

Find more on MATLAB in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!