Assume that a two-dimensional rectangular array of integers called matrix has been declared with six rows and eight columns. Write a for loop to exchange the contents of the second column with the fifth column.

Respuesta :

Debel

Answer & Step-by-step explanation:

 //written in java

// program uses a for loop to exchange the contents of the second column with the fifth column in a six rows and eight columns array

public class Main{

   public static void main(String[] args) {

       //specifying an integer to hold values during swap

       int  value = 0;

       //sample array of

       int[][] arr = {

               {1, 2, 3, 4, 5, 6, 7, 8},

               {1, 2, 3, 4, 5, 6, 7, 8},

               {1, 2, 3, 4, 5, 6, 7, 8},

               {1, 2, 3, 4, 5, 6, 7, 8},

               {1, 2, 3, 4, 5, 6, 7, 8},

               {1, 2, 3, 4, 5, 6, 7, 8},

       };

       //loop to swap column 2 and column 5

       for (int i = 0; i < arr.length; i++) {

           for (int j = 0; j < arr[i].length; j++) {

               if(j==1){

                   value = arr[i][j];

               }

               if(j==4){

                   arr[i][1] = arr[i][j];

                   arr[i][j] = value;

               }

           }

       }

       

       //loop to print out result

       for (int[] ints : arr) {

           for (int anInt : ints) System.out.print(" " + anInt);

           System.out.print("\n");

       }

   }

}