Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I need help with this simple coding activity. I will award full points to the fi

ID: 643523 • Letter: I

Question

I need help with this simple coding activity. I will award full points to the first person whos code works. I would appreciate it if you included a small explanation of what it is you're doing so that I can understand.

You have an array of 5 integers: 5,4,3,2,1. Prompt the user for 2 values. The two integers will represent indexes within the array. You must swap the values in the two indexes, and then print out the array. Each value of the array should be printed on its own Line. If the numbers given to you are out of bounds, do not swap any elements, and print the array.

Explanation / Answer

#include <iostream>

using namespace std;

int main()
{
   int my_array[] = { 5, 4, 3, 2, 1 };
   int a, b;
   cout << "enter two number:";
   cin >> a >> b;//reading the two numbers
   if (a >= 5 || b >= 5)// if 'a' and 'b' are out of bound
   {
       for (int i = 0; i < 5; i++)
           cout << my_array[i] << " ";
   }
   else// if 'a' and 'b' are in range
   {
       //swap
       my_array[a] = my_array[a] ^ my_array[b];//^ ---> xor operation
       my_array[b] = my_array[a] ^ my_array[b];//swapping without use of another variable
       my_array[a] = my_array[a] ^ my_array[b];

       for (int i = 0; i < 5; i++)
           cout << my_array[i] << " ";
   }
}