Trying to combine For and If loop

1 回表示 (過去 30 日間)
James Blackwell
James Blackwell 2016 年 8 月 12 日
コメント済み: James Blackwell 2016 年 8 月 12 日
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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by