Home > Mobile >  How I Can Print a triangle of numbers in one line without 'dart:io'?
How I Can Print a triangle of numbers in one line without 'dart:io'?

Time:01-24

void main() {
  for(int i = 1; i < 6; i  ){
  for(int j=1; j<=i; j  ){
var str = j.toString();
     String result = str   '';
      print(result);

   }
   print('');
    
    }
  }

Or just print j getting me the same result.

That's all print in multiple lines.

I tried toString(), but nothing changed.

CodePudding user response:

Is this maybe what you want?

void main() {
  for(int i = 1; i < 6; i  ){
    String result = '';
    for(int j=1; j<=i; j  ){
      result = result   j.toString();
    }
    print(result);
  }
}

Output:

1
12
123
1234
12345

Another way is to use a StringBuffer as mentioned by @pskink which is more efficient. For example like:

StringBuffer buffer = StringBuffer();
for(int i = 1; i < 6; i  ){
  for(int j=1; j<=i; j  ){
    buffer.write(j);
  }
  print(buffer);
  buffer.clear();
}

Or another solution is like

for(int i = 1; i < 6; i  ){
  print(List.generate(i, (i) => i   1).join());
}

or even the one-liner:

print(List.generate(6, (i) => List.generate(i, (i) => i   1).join()).join('\n'));
  • Related