( need help ) nested for loops to print the following pattern

7 ビュー (過去 30 日間)
reem alromaihi
reem alromaihi 2017 年 12 月 5 日
回答済み: emad xa 2020 年 4 月 6 日
Write a nested for loops to print the following pattern
A
BA
CBA
DCBA
EDCBA
I write my own code but the output is different any one can show me where is the mistake the code is :
for letter = 'A':'E'
for n= 'A':letter
fprintf(letter)
%fprintf(n)
end
fprintf('\n')
end
and the output is :
A
BB
CCC
DDDD
EEEEE
need help
  1 件のコメント
Guillaume
Guillaume 2017 年 12 月 5 日
A one-liner to generate that matrix:
char(toeplitz(65:69, [65, 32, 32, 32, 32]))
Obviously, not likely to be an accepted answer to this homework problem.

サインインしてコメントする。

回答 (3 件)

Star Strider
Star Strider 2017 年 12 月 5 日
You have to count down from the present index of ‘letter’ in the loop to 1.
(It is difficult to illustrate it without providing the complete solution.)
Example
letter = 'A':'E';
loop with index k1
k1 = 1
print letter(k1)
k1 = 2
print letter(k1), letter(k1-1) ...
...
end loop
Use fprintf('%s'\n', ...)|* to print the concatenated letter array.

KL
KL 2017 年 12 月 5 日
編集済み: KL 2017 年 12 月 5 日
You have it almost right but I'd suggest to use for-loops for indexing through rows(lines) and columns(individual character). Also initially you can create your character vector.
For example,
charVec = 'A':'E';
now you have all the possible characters here in this variable. Next is to use your for loops,
for letter = 1:length(charVec)
...
so first loop is for number of lines, as many lines as your number of characters.
for n= letter:-1:1
now as you see, second loop starts from the value of first loop's iterator ( letter) and goes backwards until 1. Why? Because you want to print in reverse order, right?
Now, print it inside the loop and finish the rest.
  3 件のコメント
KL
KL 2017 年 12 月 6 日
for n= -1:1:letter
this is not what I suggested. Even if you corrected it, you should not print n but the n-th element in r
Stephen23
Stephen23 2017 年 12 月 6 日
@reem alromaihi: note that KL wrote "I'd suggest to use for-loops for indexing...".

サインインしてコメントする。


emad xa
emad xa 2020 年 4 月 6 日
how to do
A B C D E
A B C D
A B C
A B
A

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by