Trying to combine For and If loop
1 view (last 30 days)
Show older comments
James Blackwell
on 12 Aug 2016
Commented: James Blackwell
on 12 Aug 2016
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
0 Comments
Accepted Answer
Torsten
on 12 Aug 2016
#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.
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!