This code swaps only the first and last lines, but does not swap the 2 and 3 lines

// перевернуть двумерный массив Поменять последнюю строку с первой, предпоследнюю со второй и т. д. // Условие: матрица должна быть квадратной. function Trans(Array, n) { for (var i = 0, j = n - 1; i < n; i++, j++) { for (var k = 0; k < n; k++) { temp = Array[i][k]; Array[i][k] = Array[j][k]; Array[j][k] = temp; } // вывод полученного массива for (var i = 0; i < n; i++) { document.writeln(Array[i]); document.writeln("<br>"); } } return Array } var Array = [ [1, 2, 3, 4], [4, 5, 6, 4], [7, 8, 9, 4], [-1, -2, -3, 5] ]; var n = Array.length; // кол-во строк и столбцов var temp = 0; document.writeln("<p>"); for (var i = 0; i < n; i++) { document.writeln(Array[i]); document.writeln("<br>"); } document.writeln("<p>"); Array = Trans(Array, n); 

    3 answers 3

     function Trans(Array, n) { for (var i = 0, j = n - 1; i < n; i++, j++) { // <-- ошибка 1 и 2 for (var k = 0; k < n; k++) { temp = Array[i][k]; Array[i][k] = Array[j][k]; Array[j][k] = temp; } // вывод полученного массива for (var i = 0; i < n; i++) { document.writeln(Array[i]); document.writeln("<br>"); } } // <-- ошибка 3 return Array } 

    A couple of errors are that your code:

    1. increases ( j++ ) instead of decreasing (and goes beyond the bounds of the array)
    2. the cycle continues until i < n , instead of i < j (that is, everything will change places 2 times and it will turn out the same as it was at the beginning).
    3. and the output of the resulting array is incorrectly drawn - you output it from the inside of the cycle to exchange subarrays, but you should at the end, outside (and, accordingly, spoil i , as @Igor rightly pointed out)

    PS As @Igor suggests, you can immediately swap the subarrays, instead of element-by-element exchange.

       var Array = [ [1, 2, 3, 4], ['Vera', 'luba', 'Zina'], ['Makar', 'Grisha', 'Viniamin'], ['Net', 'Da'] ]; var rev = Array.reverse(); console.log(rev); 

         function Print(Array, n) { document.writeln("<p>"); for (var i = 0; i < n; i++) { document.writeln(Array[i]); document.writeln("<br>"); } } function Trans(Array, n) { for (var i = 0, j = n - 1; i < j; i++, j--) { var temp = Array[i]; Array[i] = Array[j]; Array[j] = temp; } return Array; } var Array = [ [1, 2, 3, 4], [4, 5, 6, 4], [7, 8, 9, 4], [-1, -2, -3, 5] ]; var n = Array.length; // кол-во строк и столбцов Print(Array, n); Array = Trans(Array, n); Print(Array, n); 

        The third error (in addition to the two from @Kromster): the var i variables in two cycles of the Trans function are the same variable. The inner loop brings it to n , so the outer loop runs only once.