'How to print star pattern using Dart [closed]
Im trying to figure out to print star pattern using Dart language which implementing logic code. The existing code I use as indent so that the star have some space. Is this the right method to do so?
void main(){
for(int i = 0 ; i< 7; i++){
var stars='';
for(int j = (7-i); j > 1 ;j--) {
stars += ' ';
}
for(int j = 0; j <= i ;j++){
stars += '* ';
}
print(stars);
}
}
Solution 1:[1]
Here is my answer write in dartpad, change starWidth to adjust star size.
Idea is get string of the star and it padding per row then printing its.
EDIT: Updated description comment for each functional
void main() {
const starWidth = 7;
// return `*` or `space` if even/odd
starGenerator(i) => i % 2 == 0 ? "*" : " ";
// just return a string full of `space`
printPad(w) => " " * w;
// cause we need `space` between `*`, length is `w * 2 - 1`,
// return a string build of star
printStars(int w) => List.generate(w * 2 - 1, starGenerator).join('');
for (int row = 1; row <= starWidth; row++) {
// cause our width with space is `starWidth * 2`,
// padding left is `padding = (our width with space - star with with space) / 2`,
// but we only need print left side (/2) so the math is simple
// `padding = width - star with without space`
var padding = starWidth - row;
print("$row:" + printPad(padding) + printStars(row));
}
}
Solution 2:[2]
void main(){
for(int i = 0 ; i< 7; i++){
var stars='';
for(int j = (7-i); j > 1 ;j--) {
stars += ' ';
}
for(int j = 0; j <= i ;j++){
stars += '* ';
}
print(stars);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | rider2501 |



