Plotting Square Consisting of '*'

I am trying to create a square consisting of '*' with for loop. I did this
a = input('enter a number:')
for ii = 1:a
for jj = 1:a
fprintf('*')
end
fprintf('\n')
end
%output=
%*****
%*****
%*****
%*****
%*****
But space needed between '*' side by side.(one character space) It needs to be seem like square. I couldn't do that. Also how can I do this like
* * * * *
* *
* *
* *
* * * * *
that with for loops. My friend said you need to use equations. But I don't know much about that. I started recently. Also If you know where can I find examples like this I would appreciate.

 採用された回答

DGM
DGM 2021 年 3 月 22 日
編集済み: DGM 2021 年 3 月 22 日

0 投票

Try this:
clc
a = input('enter a number:');
for ii = 1:a
if any(ii==[1 a])
for jj = 1:a
fprintf('* ')
end
else
for jj = 1:a
if any(jj==[1 a])
fprintf('* ')
else
fprintf(' ')
end
end
end
fprintf('\n')
end
This yields:
enter a number:6
* * * * * *
* *
* *
* *
* *
* * * * * *
The console font should be monospaced, but the problem you're running into is because the character aspect ratio is not 1. Luckily, it's somewhere close to 2, so just adding a space works out about right. It doesn't look right in the browser because the font is different here.

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2021 年 3 月 22 日

0 投票

You do not need equations.
You can work with a series of for loops:
First phase: use one for loop to print the top row. Hint: print '* ' or '* ' to give alternating * * *
Second phase: use two for loops. The outer for loop is counting how many rows you have done. It also displays the left * . Then the inner for loop prints spaces. Then after the inner for loop, print the final * and newline.
Third phase: same as the first phase, print the alternating * and space.

1 件のコメント

sky2
sky2 2021 年 3 月 22 日
Yeah I got that thank you for answer.

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

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

製品

リリース

R2020b

タグ

質問済み:

2021 年 3 月 22 日

コメント済み:

2021 年 3 月 22 日

Community Treasure Hunt

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

Start Hunting!

Translated by