Trying to combine For and If loop

1 visualización (últimos 30 días)
James Blackwell
James Blackwell el 12 de Ag. de 2016
Comentada: James Blackwell el 12 de Ag. de 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

Respuesta aceptada

Torsten
Torsten el 12 de Ag. de 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.
  1 comentario
James Blackwell
James Blackwell el 12 de Ag. de 2016
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

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by