in c Given an array arr of type int along with two int vari

in c++ Given an array  arr of type  int , along with two int  variables  i and j, write some code that swaps the values of arr[i] and arr[j]. Declare any additional variables as necessary.

Solution

To swap the elements in array:

temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;

Here sample code to test:

#include <iostream>

using namespace std;

int main()
{
int arr[] = {1,2,3,4,5};
int i = 1;
int j = 2;
int temp; // addition variable
cout << \"arr[\"<< i<<\"] = \" << arr[i] << \"\ \" << \"arr[\"<< j<<\"] = \"<<arr[j]<<endl;

//swap arr[i] and arr[j]
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
cout << \"arr[\"<< i<<\"] = \" << arr[i] << \"\ \" << \"arr[\"<< j<<\"] = \"<<arr[j]<<endl;
return 0;
}

Output:

arr[1] = 2                                                                                                    

arr[2] = 3                                                                                                    

arr[1] = 3                                                                                                    

arr[2] = 2

in c++ Given an array arr of type int , along with two int variables i and j, write some code that swaps the values of arr[i] and arr[j]. Declare any additional

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site