How do I print a sentence "Hello world!" n number of times?

91 visualizaciones (últimos 30 días)
patty
patty el 29 de Abr. de 2015
Comentada: Walter Roberson el 6 de Feb. de 2025
n is the value you would enter to display it that number of times, for example:
n = 3
the answer would be
1) Hello world!
2) Hello world!
3) Hello world!
Thanks
  3 comentarios
Star Strider
Star Strider el 29 de Abr. de 2015
You already mentioned the functions you need in your tags.
patty
patty el 29 de Abr. de 2015
Editada: James Tursa el 29 de Abr. de 2015
I tried this
n = input('Enter a number:');
for sentence = n:1
n = fprintf('%d. Hello world!', n);
disp(n:1)
end
I'm new to matlab so I was hoping someone could help me figure it out. thanks

Iniciar sesión para comentar.

Respuesta aceptada

James Tursa
James Tursa el 29 de Abr. de 2015
Editada: James Tursa el 29 de Abr. de 2015
Since you posted your code I will make some corrections for you:
n = input('Enter a number:');
for sentence = 1:n % have the indexing go from 1 to n, not reverse
fprintf('%d. Hello world!\n', sentence); % print the index, and a newline \n
end
The fprintf will print out your line. You don't need the extra disp.

Más respuestas (1)

Siyanda
Siyanda el 6 de Feb. de 2025
Editada: Walter Roberson el 6 de Feb. de 2025
n = input('Enter a number:');
for sentence = 1:n
n = fprintf('%d. Hello world!', n);
disp(n:1)
end
//Is correct
  2 comentarios
Walter Roberson
Walter Roberson el 6 de Feb. de 2025
The result of fprintf() is the number of bytes written by fprintf(). As long as n is a numeric value, that number of bytes will be greater than 1.
disp(n:1) then asks to display a vector of numbers starting from n and counting upwards by 1 with final value no greater than 1. As we have shown, n will almost certainly be greater than 1, so that vector will start from a number greater than 1 and will end at 1 -- so it will generate the empty vector. As a result, the disp(n:1) will display the empty vector.
Now, you have
n = fprintf('%d. Hello world!', n);
which is replacing n with the number of bytes printed by fprintf(). The next iteration, n will have been replaced and so it will display the updated value of n ... and then will replace n with the updated number of bytes printed. There will probably be a couple of iterations before it gets to a steady state and the number of bytes printed matches the existing value of n.
Walter Roberson
Walter Roberson el 6 de Feb. de 2025
%n = input('Enter a number:');
n = 5;
for sentence = 1:n
n = fprintf('%d. Hello world!', n);
disp(n:1)
end
5. Hello world!15. Hello world!16. Hello world!16. Hello world!16. Hello world!
Everything appears on one line because no \n format specification was given in the fprintf()

Iniciar sesión para comentar.

Categorías

Más información sobre Characters and Strings 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