Performing operation with loop index inside for-loop doesn't work as expected
5 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Taniel Goetcherian
el 13 de Oct. de 2017
Comentada: Taniel Goetcherian
el 13 de Oct. de 2017
Hi I'm trying to print an upside-down triangle of hash marks using a for loop. Here's what I've got so far:
n=input('How many hashtags would you like to print today? : ');
m=floor(n/2);
%{
'm' is the height (or rather 'depth') of the triangle,
currently only works correctly for odd numbers,
will figure out even numbers later
%}
hash(1:n)='#';
fprintf([hash '\n'])
for row=1:m
space(1:row)=' ';
fprintf(space)
new_hash(1:n-2*row)='#';
fprintf([new_hash '\n'])
%{
that new_hash bit is supposed to shorten the length
of hash marks on each iteration, why does this not work??
%}
end
So when I input 7, I get:
#######
#####
#####
#####
But I want to get:
#######
#####
###
#
Any help on how to fix this (or an entirely new approach, as long as it uses a for-loop) would be greatly appreciated.
0 comentarios
Respuesta aceptada
James Tursa
el 13 de Oct. de 2017
Editada: James Tursa
el 13 de Oct. de 2017
You don't set the trailing elements of new_hash to spaces on each iteration, or clear new_hash each iteration, so those trailing hash marks remain. What if you do this:
for row=1:m
clear new_hash
:
etc
If you are running this as a script, you will want to do this also each iteration:
clear space
Alternatively, you could set these variables directly within your loop and then not have to worry about clearing them each iteration. E.g.,
space = repmat(' ',1,row);
new_hash = repmat('#',1,n-2*row);
3 comentarios
James Tursa
el 13 de Oct. de 2017
When you use indexing on the left hand side, it is only those specific indexed elements that get changed. All of the other elements remain unchanged.
Más respuestas (0)
Ver también
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!