Print number series in java
Posted
by
user1898282
on Stack Overflow
See other posts from Stack Overflow
or by user1898282
Published on 2012-12-12T16:49:01Z
Indexed on
2012/12/12
23:04 UTC
Read the original article
Hit count: 155
I have to print the series shown below in java:
***1***
**2*2**
*3*3*3*
4*4*4*4
My current implementation is:
public static void printSeries(int number,int numberOfCharsinEachLine){
String s="*";
for(int i=1;i<=number;i++){
int countOfs=(numberOfCharsinEachLine-(i)-(i-1))/2;
if(countOfs<0){
System.out.println("Can't be done");
break;
}
for(int j=0;j<countOfs;j++){
System.out.print(s);
}
System.out.print(i);
for(int k=1;k<i;k++){
System.out.print(s);
System.out.print(i);
}
for(int j=0;j<countOfs;j++){
System.out.print(s);
}
System.out.println();
}
}
But there are lot of for loops, so I'm wondering whether this can be done in a better way or not?
© Stack Overflow or respective owner