Click here to Skip to main content
15,039,214 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi
im going to swap the first int in my arry whit the last.

C#
int[] Tal = new int[10];
Console.WriteLine("10 numbers: ");
for (int i = 0; i < Tal.Length; i++)
{
    Console.Write("number " + (i + 1) + ": ");
    Tal[i] = int.Parse(Console.ReadLine());
}
 Arra c = new Array();
 c.FirstLast(Tal)


C#
  public void FirstLast(int[] arr)
{
    foreach (int t in arr)
    {
        int temp = arr[0];
        arr[0] = arr[9];
        arr[9] = temp;
        Console.WriteLine(t);
    }


when i type in 1,2,3,4,5,6,7,8,9,10 and then it show 1,2,3,4,5,6,7,8,9,1
i want it to be 10,2,3,4,5,6,7,8,9,1. I know i replace the first whit the last but way dos it not replace the first one to whit the last.

sorry for the bad english. I hope someone will understand it
Posted

Hi,

Try this:
C#
public void SwapFirstAndLast(ref int[] array)
{
     int temp = array[0];
     int posOfLast = array.Length - 1;
     array[0] = array[posOfLast];
     array[posOfLast] = temp;
}

How to use this swap method:
C#
SwapFirstAndLast(ref intArray); // change intArray into the name of your array

More about the ref keyword: http://msdn.microsoft.com/en-us/library/14akc2c7.aspx[^]

Hope this helps.
   
Comments
zxcvasdf1 10-Mar-13 13:42pm
   
thx for this i will try this is always good to learn something new
Thomas Daniels 10-Mar-13 13:43pm
   
You're welcome!
You should probably take the swapping code out from the foreach loop:
C#
public void FirstLast(int[] arr)
{
    int temp = arr[0];
    arr[0] = arr[9];
    arr[9] = temp;

    foreach (int t in arr)
    {
        Console.WriteLine(t);
    }
}


And, yes definitely use ref in function call that swaps the values so that you can show your result in console, window or what do I know maybe return as value in another function.

Happy coding.
   
v2
Comments
zxcvasdf1 10-Mar-13 13:41pm
   
thx for the help it workts
C#
 int j = 9;
int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int[] arr2 = new int[10];
for (int i = 0; i < arr.Length; i++)
{
   arr2[j--] = arr[i];
   Console.WriteLine(arr2[i]);
}
for (int i = 0; i < arr2.Length; i++)
{
    Console.WriteLine(arr2[i]);

}
Console.ReadKey();
   
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900