Reputation: 25
I wrote a program on Matlab that checks how many numbers are divisable by 2 starting from 1 to integer N (that is set by the user)
Here's my code:
num=input('Please enter a number');
count=0;
while (num>=0);
if mod(num,2)==0;
count=count+1;
end
num=num-1;
end
disp(count)
I've tried to run this code but it doesn't output anything. I hope someone can help me figure out what is wrong it Please note that we haven't studied it in school, I just read online and tried to write something on my own.
Upvotes: 1
Views: 151
Reputation: 2488
I see many logical errors in your code. To begin with you are checking if num
is divisible by 10
, not 2
. Also you should decrement num
regardless if it passes the if condition, if you want to check the next number. Finally you say you want to check numbers ranging 1 to N
but your while loop actually checks numbers 0 to N
, due to the >=
condition.
From a syntactical point of view: if's and while's (and for's) should not have a trailing semicolon after them.
So maybe something like this could be closer to what you are asking, albeit I still don't know if I fully understand your problem.
% Ask for user input
num = input('Please enter a number');
count = 0;
while (num > 0)
% Check for divisibility
if mod (num, 2) == 0
count = count + 1;
end
% Decrement number
num = num - 1;
end
% Display the count -- writing the variable name without an ending semicolon ';' causes Matlab to output the variable content
count
Upvotes: 1
Reputation: 16214
No need in loop, use Matlab the way it was designed for
num = input('Please enter a number ');
count = sum(mod(1 : num, 2) == 0);
disp(count);
Upvotes: 1