Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Ragged Arrays It is also possible to make each of the rows of an array a differe

ID: 3805014 • Letter: R

Question

Ragged Arrays It is also possible to make each of the rows of an array a different size. This is called a "ragged" or "jagged" array. Ragged arrays can be quite useful if you have a list of lists, but each list can be a different length. You declare a ragged array by first declaring an array to hold all the rows, and then declaring each row separately in a loop, as shown in the code below. Part 4) Start with the a copy of Lab8bjava (shown below). Fill in the code to create a subtraction table with all the non-negative elements of the table. Lab 8b

Explanation / Answer

Here is the solution-

//Note :- please change the output file(outTriangle.txt) location inside writeOutputToFile(int table[][]) method before executing the below program.

public class Lab8b {

   public static final int SIZE = 10;

   /**main method to test the program
   *
   * @param args
   */
   public static void main(String[] args) {
       int table[][] = new int[SIZE][SIZE + 1];
      
       //loop for filling content in ragged array
       for (int r = 0; r < table.length; r++) {
           for (int c = 0; c < table[r].length; c++) {
               table[r][c] = r - c;
           }
       }

       //loop for printing ragged array content
       for (int r = 0; r < table.length; r++) {
           for (int c = 0; c < table.length; c++) {
               System.out.print(table[r][c] + " ");
           }
           System.out.println(); //adding new line after printing all columns
       }

       writeOutputToFile(table); //calling method to print the ragged array content into file
   }

   /**method to write array content into outTriangle.txt file
   *
   * @param table
   */
   private static void writeOutputToFile(int table[][]) {
       try {
           FileWriter writer = new FileWriter(
                   "fileLocation\outTriangle.txt");// output file location
           BufferedWriter bufferedWriter = new BufferedWriter(writer);
          
           for (int r = 0; r < table.length; r++) {
               for (int c = 0; c < table.length; c++) {
                   bufferedWriter.write(table[r][c] + " ");
               }
               bufferedWriter.write(" "); //adding new line after printing all columns
           }

           bufferedWriter.close();
       } catch (IOException e) {
           e.printStackTrace();
       }

   }
}