Trying to combine For and If loop

2 次查看(过去 30 天)
I watched a video on the 3n + 1 conjecture and just wanted to try and see if I could create a simple program to replicate a few cycles of it.
What I would like to do is make it so that the program takes an input number, decides if it's odd or even. If even divide it by 2 and then use that number to continue the loop. Or if the value is odd multiply it by 3 and add 1 and then continue the loop.
i.e if the number was 7, it's odd so go to 22, that's even so go to 11, that's odd so go to 34, that's even so go to 17 and so on.
Here's my attempt at it, I just wanted to try it for fun and got nowhere. I'm hoping it's just something small I have to do with the code, if not I can leave it.
#Want to do 10 loops of n
#If n is even /2
#if n is odd n*3 +1
n = input("enter first value for n")
for i = (n:10);
disp(i)
if mod(i, 2) == 0
% i is even
ans = sprintf("%d", i ," is even")
newn = (i/2)
disp(ans)
else
% i is odd
ans = sprintf("%d", i ," is odd")
disp(ans)
newn = (3*n +1)
end
end

采纳的回答

Torsten
Torsten 2016-8-12
#Want to do 10 loops of n
#If n is even /2
#if n is odd n*3 +1
n = input("enter first value for n")
for i = 1:10
disp(n)
if mod(n, 2) == 0
% n is even
ans = sprintf("%d", n ," is even")
n = n/2
disp(ans)
else
% n is odd
ans = sprintf("%d", n ," is odd")
disp(ans)
n = 3*n +1
end
end
Best wishes
Torsten.
  1 个评论
James Blackwell
James Blackwell 2016-8-12
Thank you Torsten! I thought it was something simple but just couldn't see it. Simplified it down to.
n = input("enter first value for n")
for i = 1:10
if mod(n, 2) == 0
% n is even
n = n/2
else
% n is odd
n = 3*n +1
end
end
All the best James

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by