java - printing rhombus numbers using a single loop? -
i talking printing pattern
1 121 12321 1234321 123454321 12345654321 1234567654321 123456787654321
it easy using more single loop. trying implement using single loop not able so. possible?
my code:- stringbuilder sb = new stringbuilder(); (int = 1; <= 8; ++i) { system.out.println(sb.append(i) + new stringbuilder(sb).reverse().substring(1));
but see how possible see being used out predefined functions reverse() etc available use loop inside them. simple single "for" loop.
here way write out pattern using 1 loop:
class rhombusnumbers{ public static void main(string[] args){ string left = ""; int max = 8; for(int = 1; <= max; i++){ system.out.println(left + + new stringbuilder(left).reverse().tostring()); left+=i; } } }
it keeps track of left digits , adds new digit on every time.
edit:
without stringbuilder since stringbuilder.reverse() uses loop , reverse 10:
class rhombusnumbers{ public static void main(string[] args){ string left = ""; string right = ""; int max = 8; for(int = 1; <= max; i++){ system.out.println(left + + right); left+=i; right = + right; } } }
Comments
Post a Comment