Search code examples
javaloopsnestedbluej

Output in nested loops


I'm trying to get this output:

123454321
1234 4321
123   321
12     21
1       1

I have tried doing this first:

12345
1234
123
12
1

Then,putting a '\t' and putting this next to the above:

4321
4321
321
21
1 

Solution

  • The below code gives the output you mentioned

    package com.hello;
    
    public class Test {
    
    /**
     * @param args
     */
    public static void main(String[] args) {
        printNumbers(5,5);
    }
    
    private static void printNumbers(int max,int iteration)
    {
        String line ="";
        int NoOfSpaces = (max-iteration)*2 -1;
    
        if(iteration == 0)
            return;
        for(int i=1;i<=iteration;i++)
            line = line+i;
        for(int i =0;i<NoOfSpaces;i++)
            line = line+" ";
        if(max != iteration)
            line = line +iteration;
        for(int i=iteration-1;i>=1;i--)
            line = line +i;
        System.out.println(line);
        printNumbers(max,--iteration);
    
      }
    }
    

    let me know if you have any further questions....