Make a vector out of all even/odd numbers from 1 to 100 using for and if

조회 수: 38 (최근 30일)
Hello, I'm to make two vectors: one consisting of all even numbers between 1 and 100 and one of all the odd numbers. I have to use only simple for and if cycles.
My attempt:
j=1;
k=1;
for i=1:100
if mod(i,2)==0 && i~=1
even(j)=i;
j=j+1;
else
odd(k)=i;
k=k+1;
end
end
even
odd
Now the odd part works well but the even part doesn't. This is what it prints out:
Columns 1 through 22
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44
Columns 23 through 44
46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88
Columns 45 through 66
90 92 94 96 98 100 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
Columns 67 through 88
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
Columns 89 through 100
89 90 91 92 93 94 95 96 97 98 99 100
So it prints all even numbers, which is great, but then it prints every number from 51 to 100. Why? When I type in mod(51,2) it says 1 so the condition doesn't apply.
(Posted on here a couple of minutes ago, hope that's allowed)

답변 (5개)

James Tursa
James Tursa 2018년 3월 15일
편집: James Tursa 2018년 3월 15일
You probably have left-over variables from a previous run that you are writing into. Clear them out first. E.g., put this at the top of your code:
clear even odd
  댓글 수: 3
James Tursa
James Tursa 2018년 3월 15일
Scripts run in your current workspace and leave all resulting variables in your workspace. Sometimes this is what you want, but often it is not. I very seldom use scripts ... almost everything I write is a function, even if it takes no inputs. That way I know I am starting with a fresh workspace for the new code and that I am not corrupting my current workspace. E.g., if your code had been in a file called even_odd.m like this:
function even_odd
% your code
end
you would not have encountered the error that you did. Then if you wanted it to operate on an arbitrary n value and return a result, it is easy to modify. E.g.,
function [even,odd] = even_odd(n)
:
for i=1:n
:
end
Etc.

댓글을 달려면 로그인하십시오.


K. KARTHIK KUMAR
K. KARTHIK KUMAR 2019년 12월 16일
  1. Create a vector of all the odd positive integers smaller than 100 in increasing order and save it into variable odds.
  2. Create a vector of all the even positive integers smaller than or equal to 100 in decreasing order and save it into variable evens.

Lenny C
Lenny C 2020년 1월 27일
For doing the even part initialize the value of k=50 and change for statement to for i=100:-1:1 and change the value of k from k+1 to k-1(this prints even number in reverse order .

Sajjad Ahmad Khan
Sajjad Ahmad Khan 2020년 1월 30일
Hi you need to change it as per odd/even number.

sebastian Muñoz Aponte
sebastian Muñoz Aponte 2020년 7월 27일
ayuadame

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by