pattern printing using for loop




Asked on February 25, 2015
how to print the following pattern using single for loop?
1
12
123
1234
12345
1234
123
12
1



Replied on February 25, 2015
package programs;

public class ForLoopTest {
public static void main(String[] args) {
int i = 12345;
   for(int j=4;j>-5;j--)
   {
       int p = i/(int)Math.pow(10,Math.abs(j));
       System.out.println(p);
   }
}

}




Replied on February 25, 2015
public void test() {
    String template = "12345";
    for (int i = 1; i < 10; i++) {
        System.out.println(template.substring(0, i <= 5 ? i : 5 - (i - 5)));
    }
}

or 

public void test() {
    String template = "12345";
    for (int i = 4; i >= -4; i--) {
        System.out.println(template.substring(0, 5 - Math.abs(i)));
    }
}



Replied on February 25, 2015
1- using only a for loop (with no "hidden loop" such as substring)

2- which takes a parameter indicating the maximum number to print (contrary to the log10 based solutions)

3- in Java.


class loop1{
public static void main(String[] args) throws Exception {
   printUpTo(5);
}

public static void printUpTo(int upperBound) {
   int number = 1;
   int nextNumber = 1;
   for (int i = 0; i < upperBound * upperBound; i++) {
       System.out.print(number);
       if (number == nextNumber) {
           if (i < (upperBound * upperBound / 2)) {
               nextNumber++;
           } else {
               nextNumber--;
           }
           number = 1;
           System.out.println();
       } else {
           number++;
       }
   }
}
}


Write Answer











©2024 concretepage.com | Privacy Policy | Contact Us