First, in the program, the largest and smallest elements of the matrix are reversed, and then each row should be ordered in descending order, but only the modified matrix1 is displayed to me. What's wrong?

Console.WriteLine("Введите k"); int k = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Введите n"); int n = Convert.ToInt32(Console.ReadLine()); int[,] a = new int[k, n]; int max = int.MinValue; int min = int.MaxValue; Random random = new Random(); for (int i = 0; i < k; i++) { for (int j = 0; j < n; j++) a[i, j] = random.Next(0, 10); } Console.WriteLine("Исходная матрица:"); for (int i = 0; i < k; i++) { for (int j = 0; j < n; j++) Console.Write("{0,4}", a[i, j]); Console.WriteLine(); } int iMax = 0, jMax = 0, jMin = 0, iMin = 0; for (int i = 0; i < k; i++) { for (int j = 0; j < n; j++) { if (a[i, j] > max) { max = a[i, j]; iMax = i; jMax = j; } if (a[i, j] < min) { min = a[i, j]; iMin = i; jMin = j; } } } a[iMin, jMin] = max; a[iMax, jMax] = min; Console.WriteLine("Измененная матрица1:"); for (int i = 0; i < k; i++) { for (int j = 0; j < n; j++) Console.Write("{0,4}", a[i, j]); Console.WriteLine(); } Console.WriteLine("Измененная матрица2:"); int x = 0; for (int m = 0; m < k; m++) for (int j = 0; j < n; j++) { if (a[m, j] < a[m, j++]) { x += a[m, j]; a[m, j] = a[m, j++]; a[m, j++] = x; } } for (int i = 0; i < k; i++) { for ( int j = 0; j < n; j++) Console.Write("{0,4}", a[i, j]); Console.WriteLine(); } Console.WriteLine(); Console.ReadLine(); 
  • 2
    Your algorithm is wrong. I advise you to start by writing it with a pseudocode "on a piece of paper", then it will be easy to write it down in terms of C# . - user227049
  • Which sorting algorithm do you want to apply? - user227049
  • elements of each line descending @FoggyFinder - grin
  • Hmm, meant a little more. Let's take the most obvious - bubble sorting. Do you know her principle? - user227049
  • 3
    not really. Imagine that a matrix row is just a separate data set that is not related to the rest. Try to write code to sort a one-dimensional array, if you succeed correctly, then you can easily add an external loop that will move along the rows of the matrix. - user227049

1 answer 1

This resource is not intended to correct homework. Nevertheless, I will analyze the main errors in detail, and how to apply them to your decision will have to think on your own. You did not come here for free, but for knowledge?

1. Using the operator ++

The ++ operator is a combined operator that increases the current value of a variable by 1. I draw attention to the fact that this change is not temporary, but permanent. A few examples:

The simplest case

 x++; //или ++x; //эквивалентная запись x = x + 1; 

In compound terms
First case (increase by one after use)

 int x = 1, y = 0; y = x++; //эквивалентная запись y = x; x = x + 1; //в результате y=1, x=2 

Second case (increase by one before use)

 int x = 1, y = 0; y = ++x; //эквивалентная запись x = x + 1; y = x; //в результате y=2, x=2 

All the same applies to the operator -- . I think the difference is not difficult to notice.

2. Operator + =

With this operator it is easier to go straight to the equivalent record:

 x += y; //эквивалент x = x + y; //но никак не x = y; 

You should not use abbreviated expressions if you don’t understand how it works. Abbreviated entries are intended to reduce the amount of code of really large programs, and in training programs they only confuse the understanding of how the algorithm works.

Now pay attention to the fragment from your code:

 //первый проход по циклу for (int j = 0; j < n; j++) //предполагается, что значение j уведичится после окончания цикла, //а во время выполнеия будет равно 0 { if (a[m, j] < a[m, j++])//сравниваем a[m,0] и a[m,0] //увеличение после использования. после сравнения j = 1 { //код который был тут никогда не выполнится, т.к. x < x == false } //первый проход закочен, цикл увеличивает счестчик на один //на втором проходе j = 2, а должно быть 1. } 

There are two errors here. The first is to never use the ++ operators and -- to the for loop counter inside the loop itself, this disrupts the sequence of values ​​accepted by the counter, in any case, until you get comfortable with the basic algorithms. And the second - the incorrect application of the poerator ++ led to the comparison of incorrect elements, instead it was necessary to write j+1 .

OK. Correct if , what next?

 for (int j = 0; j < n; j++) { if (a[m, j] < a[m, j+1]) { x += a[m, j];//вы уверены, что хотите получить в x сумму всех подходящих элементов? a[m, j] = a[m, j++];//a[m,j] = a[m,j], а смысл? a[m, j++] = x;//тут вроде бы все хорошо, a[m, j+1] = x, //только вот значение a[m, j+1] затерлось новым значением //ну и счетчик цикла, как и в прошлый раз сбился, если в первый раз //через один, то теперь через два. } } 

3. Why sorting does not work

Let's start with the fact that the presented code fragment does not contain a sorting algorithm.

Three simple sorting algorithms should tell you:
- bubble sorting
- sort by choice
- sorting inserts

Thus, in relation to the matrix and the expected result, the algorithm should look like this (pseudocode)

 //для каждой строки матрицы for(int i = 0; i < n i++) { //Сортируем строку с индексом i } 

Any of the above sorting algorithms is easy to find on the network by its name, including the working C # source code, so it will also remain for independent work.

Practical advice: do not limit yourself to simply copying the found source, understand how it works and practice on a one-dimensional array, as @Foggy Finder has already advised in the comments.

Then apply the same algorithm to the row of the matrix, the only difference will be that for a two-dimensional array, the row number will be set to a variable from the outer loop.