MATLAB: Finding all numbers which is divisible by 5

homeworkmodwhile loop

Hello,
I would like to write a program which identifies all number which divisible by 5 by using while loop and mod.
Here is what I have so far.
a=input('Enter the threshold: ');
disp('Following number is devided by 5' + a);
number = 1;
while number<=a
if mod(a,5)==0
disp(a);
end
number=number+1
end
disp("The following numbers are divisible by 5: " + mod)
and the outcome display should look like this…
Enter the threshold: 100(For example)
The following numbers are divisible by 5: 5, 10, 15, 20 …100(For example of threshold 100)
I really appreciate your response in advance!

Best Answer

Hi,
In your mod command you want to compare the number variable to 5, not a (a doesn't change). This is why you're getting unexpected results. I would use zeroes to initialize z so that you can save each number that is divisible by 5 like:
a=input('Enter the threshold: ');
number = 1; z = zeros(1,a);
while number <= a
if mod(number,5) == 0
z(number) = number;
end
number=number+1;
end
And then use
find
to extract the indices of z that are nonzero and print them out.
I hope this helped