Answer the question
In order to leave comments, you need to log in
Help finding a bug in a C# program, arrays
Problem statement: It is necessary to find the minimum element of the array (we will assume that it is the only one) and move the column with this element to the place of the first one;
Problem: 1) Finds the minimum incorrectly
2) Doesn't change the columns
PS sorry for the code, I'm just learning :)
int[,] A = new int[n, n];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
A[i, j] = Convert.ToInt32(dataGridView1.Rows[i].Cells[j].Value);
}
int min = A[0, 0], min_j = -1;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
if (min < A[i, j])
{
min = A[i, j];
min_j = j;
}
}
if (min_j != 0) ;
{
int rez;
for (int i = 0; i < n; i++)
{
rez = A[i, 0];
A[i, 0] = A[i, min_j];
A[i, min_j] = rez;
label1.Text = Convert.ToString(min);
}
}
Answer the question
In order to leave comments, you need to log in
In the IDE, you can press F9 for each line of code and see step by step where exactly the error has crept in. Plus, when you click on an error, the Error List will direct you to the desired line.
In the line if (min_j != 0) ; You need to remove the semicolon if I'm not mistaken.
You don't need a nested loop.
External do from 1 to n.
Make substitutions according to the algorithm:
rez = A[i, min_j];
A[i, min_j] = A[i, 0];
A[i, 0] = rez;
if (min < A[i, j])
Why less? If the minimum is less than some value, this is normal. To find the minimum, you still need (min > A[i, j])
int min = A[0, 0], min_j = -1;
...
if (min_j != 0) ;
Thank you very much! it remains to solve the problem by changing the columns, I tried to apply the following algorithm (carefully bydlokoda):
<code lang="cs">
if (min_j > 0)
{
int rez;
for (int i = 0; i > -1; i--)
{
for (int j = min_j; j > -1; j--)
{
rez = A[i, j];
A[i, j] = A[i, j + 1];
A[i, j + 1] = rez;
}
}
}
</code>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question