Drawing this shape using *

How to draw This Shape
*
* *
* *
* *
* *
I tried to play around some nested loops and didn't work for me

 Accepted Answer

This takes me back to my FORTRAN days in the late 1960s when line printer code similar to this was the only option for plotting.
Try this:
spc = uint16(' ');
ast = uint16('*');
tringl = char(ones(6,6,'uint8')*32);
for k1 = 2:size(tringl,1)
tringl(k1,[8-k1,4+k1]) = ast;
end
for k1 = 1:size(tringl,1)
fprintf(1, '%s\n', tringl(k1,:))
end
Experiment to get the result you want.

7 Comments

is there by any means a chance that this could be possible using nested loops ? I created a code in C++ tried to convert it line by line to matlab but didn’t fet the correct output
Sure.
Define a matrix of spaces, then in each iteration of the loop insert an asterisk at the correct location, and print the matrix. You can do the same line-by-line, printing each line as you create it, without first creating the matrix.
There are many different ways to do this.
can you show me how to do the line by line thing i'm kinda new to MATLAB I did this on c++ tried to translate it to MATLAB but didn't give the same output
#include <iostream>
using namespace std;
int main()
{
int n = 5;//number of rows
int i, j, k = 0;
for (i = 1; i <= n; i++) // <=n <=5 number of rows is 5 This loop will repeat 5 times for each line print
{
//The loop to Print spaces
for (j = i; j < n; j++) {
cout << " ";
}
//The loop to Print *
while (k != (2 * i - 1)) {
if (k == 0 || k == 2 * i - 2)
cout << '*';
else
cout << " ";
k++;
}
k = 0;
cout << endl; // print next row
}
}
I haven’t programmed in any version of C since I began with MATLAB more than two decades ago. Unfortunately, I cannot help you convert your C++ code to MATLAB code.
Kenan Baira’s ‘Answer’ moved here:
i did it myself i know how to create a for loop with starting value and increment and when to stop and while loop with the != which means not equal to made it ~= and all that but it didn’t work at all i got the first line 1 star correct then every other line contains 2 stars touching
Anyways thanks for the help
What is your current code?
My pleasure.
Index the character array to fill stars from the centre to each side, incrementing by 1 in each iteration.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!