Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing the patterns using only one loop

I have printed this pattern using one loop:

*
**
***
****
*****

String s = "";
for (i = 1; i <= n; ++i) {
    s += "*";
    System.out.println(s);
}

Now i want how to print following patterns using only one loop.

1)
    *
   * *
  * * *
 * * * *
* * * * *

2)
  * * * * * 
   * * * *
    * * *
     * *
      *

3)
   1 2 3 4 5
   1 2 3 4
   1 2 3 
   1 2
   1

and other similar patterns using only one loop, I have done all of them using more than one loop.

like image 766
coder005 Avatar asked Feb 19 '23 03:02

coder005


1 Answers

I want optimization. The time complexity of two loops will be O(n^2) whereas for only one loop it will be O(n). And O(n) < O(n^2).

You realise that 99.999% of the time will be spent updating the console. If you want to save time, don't write anything. The time taken to loop is trivial by comparison.

BTW The number of stars you produce will be O(N^2) so the time complexity with be O(N^2) whether you use 1, 2 or 3 loops.

like image 189
Peter Lawrey Avatar answered Feb 27 '23 06:02

Peter Lawrey