Ask Question
21 May, 17:59

Write a method swaparrayends () that swaps the first and last elements of its array parameter. ex: sortarray = {10, 20, 30, 40} becomes {40, 20, 30, 10}. the array's size may differ from 4.

+5
Answers (1)
  1. 21 May, 19:53
    0
    In the C programming language, you can't determine the array size from the parameter, so you have to pass it in as an extra parameter. The solution could be:

    #include

    void swaparrayends (int arr[], int nrElements)

    {

    int temp = arr[0];

    arr[0] = arr[nrElements - 1];

    arr[nrElements - 1] = temp;

    }

    void main ()

    {

    int i;

    int myArray[] = { 1,2,3,4,5 };

    int nrElements = sizeof (myArray) / sizeof (myArray[0]);

    swaparrayends (myArray, nrElements);

    for (i = 0; i < nrElements; i++)

    {

    printf ("%d ", myArray[i]);

    }

    getchar ();

    }

    In higher languages like C# it becomes much simpler:

    static void Main (string[] args)

    {

    int[] myArray = {1, 2, 3, 4, 5};

    swaparrayends (myArray);

    foreach (var el in myArray)

    {

    Console. Write (el + " ");

    }

    Console. ReadLine ();

    }

    static void swaparrayends (int[] arr)

    {

    int temp = arr[0];

    arr[0] = arr. Last ();

    arr[arr. Length - 1] = temp;

    }
Know the Answer?
Not Sure About the Answer?
Find an answer to your question ✅ “Write a method swaparrayends () that swaps the first and last elements of its array parameter. ex: sortarray = {10, 20, 30, 40} becomes ...” in 📘 Computers and Technology if you're in doubt about the correctness of the answers or there's no answer, then try to use the smart search and find answers to the similar questions.
Search for Other Answers