how to get the even numbers between 2 numbers using a loop
24 views (last 30 days)
Show older comments
So, for example, between 5 and 13 it would show: [6 8 10 12]
1 Comment
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...
Accepted Answer
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
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.
More Answers (1)
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
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!