Performing operation with loop index inside for-loop doesn't work as expected
5 views (last 30 days)
Show older comments
Taniel Goetcherian
on 13 Oct 2017
Commented: Taniel Goetcherian
on 13 Oct 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 Comments
Accepted Answer
James Tursa
on 13 Oct 2017
Edited: James Tursa
on 13 Oct 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 Comments
James Tursa
on 13 Oct 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.
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!