-5

I have been struggling with this pattern,trying to use only the code required for a nested FOR loop. I am required not to use patterns,just a nested for loop:

123454321
1234 4321
123   321
12     21
1       1

The code required is Java and I am using BlueJ compiler.

Burkhard
  • 14,112
  • 22
  • 84
  • 106

2 Answers2

4

Here you go. A nested for loop, which gives the desired output.

String s[] = new String[]{"123454321","1234 4321","123   321","12     21","1       1"};
for(int i=0; i<=0;i++)// for the nested loop
  for(String x:s)
    System.out.println(x);
Burkhard
  • 14,112
  • 22
  • 84
  • 106
0

You should seriously consider revising your question and be more specific. Also, you don't really need a nested loop, it seems inefficient this way. However, since you require that, here is a naive solution:

final int LIMIT = 5; //LIMIT has to be <10

//first construct a char array whose maximum number is LIMIT
char[] input = new char[2*LIMIT-1];     
//if you use Arrays.fill(input, ' '); here, and a print in the first loop, you get the reverse answer (try it)           
for (int i = 0; i<LIMIT; ++i) {
    input[i] = Character.forDigit(i+1, 10); //converts int to char (in decimal)
    input[(2*LIMIT)-i-2] = input[i];        
}


//next print the array, each time removing the chars that are within an increasing range from the middle element of the array    
for (int i = LIMIT; i > 0; --i) {            
    for (int j = 0; j < LIMIT-i; ++j) { //you don't really need a nested loop here
        input[LIMIT-1+j] = ' '; //replace the j chars following the middle with whitespace
        input[LIMIT-1-j] = ' '; ////replace the j chars before the middle with whitespace
    }
    System.out.println(input);
}

An alternative, without a nested loop, would be:

//after the first loop
String line = input.toString();

System.out.println(line);
for (int i = LIMIT; i>0; --i) {
    line = line.replace(Character.forDigit(i, 10), ' ');
    System.out.println(line);
}
vefthym
  • 7,108
  • 5
  • 26
  • 55