java - How to print a series of natural no.s in the form of two Pyramids , one normal and one inverted using single for loop? -


i trying generate kind of pattern based on user input .here input num=7

output

1

1 2

1 2 3

1 2 3 4

1 2 3 4 5

1 2 3 4 5 6

1 2 3 4 5 6 7

1 2 3 4 5 6

1 2 3 4 5

1 2 3 4

1 2 3

1 2

1

to achieve ,i came code :

import java.util.scanner; class test { public static void main(string arr[]) {     scanner input=new scanner(system.in);     system.out.println("enter no print symmetrical pyramid :");     int num=input.nextint();      //printing normal pyramid     for(int i=0;i<=num;i++)    {        for(int j=1;j<i;j++)        {            system.out.print(j);         }         system.out.println("");       }     //middle      for(int i=1;i<=num;i++)     {         system.out.print(i);     }     system.out.println("");      //printing inverted pyramid      for(int i=num;i>=0;i--)     {        for(int j=1;j<i;j++)        {            system.out.print(j);         }         system.out.println("");      }  } } 

how can achieve same output using 1 loop ?

thanks in advance !! :)

you use stringbuilder , add/remove in loop

stringbuilder sb = new stringbuilder(); (int i=0; i<=(num*2)-1; i++) {     if (i<num) {         sb.append(i+1);     } else {         sb.deletecharat(sb.length()-1);     }     system.out.println(sb.tostring()); } 

Comments

Popular posts from this blog

unity3d - Rotate an object to face an opposite direction -

angular - Is it possible to get native element for formControl? -

javascript - Why jQuery Select box change event is now working? -