Search code examples
javaarraysstringnested-loops

Printing a half pyramid from array elements


I'm pretty new to Java, just started learning it. I've got an array of numbers, with array length origArraySize:

29.50   10.80   16.40   87.80   12.20   63.70   13.90   25.00   77.40   97.40

I'm trying to arrange them in this format:

29.50
10.80   16.40
87.80   12.20   63.70
13.90   25.00   77.40   97.40

While I've seen similar half Pyramid questions, i just can't seem to figure out how to implement an array to print the numbers. Here's what I got so far, just a method of class rn:

public String toString() {
    String t = "";
    for (int i = 0; i < this.origArraySize; i++) {
        t += String.format("%8.2f", array[i]);
        for (int j = 0; j < i; j++) {
            System.out.println(t + "\n");
        }
    }
}

I know it includes nested for loops but I just can't seem to get it. The method toString() has to return String value, and I'm not sure how to implement that at the end either, but for now I tried with t.


Solution

  • You do not want an inner loop, you just need a couple of counters

    double arr[] = {29.50,10.80,16.40,87.80,12.20,63.70,13.90,25.00,77.40,97.40};
    
    int loop = 0;
    int printAtNum = 0;
    
    for (double d : arr) {
        System.out.printf("%8.2f", d); // always print
        if (loop == printAtNum) {
            System.out.println(); // only print if loop is equal
                                  // to incremented counter
            loop = 0;       // reset
            printAtNum++;   // increment
        } else {
            loop++;
        }
    }
    

    output

       29.50
       10.80   16.40
       87.80   12.20   63.70
       13.90   25.00   77.40   97.40