Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

basic c# question

Tags:

c#

.net

why doesn't the element get swapped

public static void SwapArray(int[,] arr)
    {
        for (int i = 0; i < arr.GetLength(0); i++)
        {
            for (int j = 0; j < arr.GetLength(0); j++)
            {
                int temp = arr[i, j];
                arr[i, j] = arr[j, i];
                arr[j, i] = temp;
            }
        }
    }

even if the parameter is without a ref modifier the array doesn't change. a copy of the reference is passed as a parameter right?

like image 426
CoffeeCode Avatar asked Apr 07 '10 07:04

CoffeeCode


People also ask

What is basic C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

Which is basic C or C++?

C is the foundational, procedural programming language introduced earlier for system applications and low-level programs. C++ is an Object-oriented programming language with features same as C and additional features like Encapsulation, Inheritance, etc for complex application development.

What are the basic C syntax?

The basic syntax of the C program consists of header, main() function, variable declaration, body, and return type of the program. The header is the first line in the C program with extension . h which contains macro definitions and C functions.


1 Answers

There is an error in your algorithm. For every i and j, your loop swaps arr[i,j] and arr[j,i] twice.

For example arr[3,1] gets swapped with arr[1,3] once for i=3, j=1 and once for i=1, j=3. So the result is the original matrix. You should change the j-loop to

for (int j = 0; j < i; j++) 
like image 79
Jens Avatar answered Sep 24 '22 17:09

Jens