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

In C++ Write a program to swap an array element (array A) with the element at tw

ID: 3767384 • Letter: I

Question

In C++ Write a program to swap an array element (array A) with the element at twice its index position. If twice the index position does not exist, no swapping will happen. Store this in a new array (array B) and store the sum of the original and new array in another array (array C). Find the minimum of the left half of the final array C. Input array A size and elements. Please submit output screenshots with both odd and even number array sizes.

For example,

Say, size = 10 and array A elements input are 4 5 8 12 34 56 1 0 22 7

Array A= 4 5 8 12 34 56 1 0 22 7

Array B

Swap 0 and (2 * 0 = 0) indexed elements

45 8 12 34 56 1 0 22 7

Swap 1 and 2 indexed elements

4 8 512 34 56 1 0 22 7

Swap 2 and 4 indexed elements

4 8 3412 556 1 0 22 7

Swap 3 and 6 indexed elements

4 8 34 15 56 120 22 7

Swap 4 and 8 indexed elements

4 8 34 1 225 56 0 57

5 * 2 = 10 which exceeds the last index (9) of the array, so swapping stops.

Array C= Array A + Array B = 8 13 42 13 56 61 6 0 27 14

Left half of array C = 8 13 42 13 56

Min= 8

If odd number of elements in array (size is an odd number ­ then left half= = (size+1)/2)

Explanation / Answer

#include <iostream>

using namespace std;

void swap(int &a,int &b)

{

int temp;

temp = a;

a = b;

b = temp;

}

int main()

{

int size;

cout << "Input the size of array : ";

cin >> size;

  

int A[size];

int B[size],C[size];

int index;

  

for(int i=0;i<size;i++)

{

cout<<"Input number " << i+1 << " : ";

cin >> A[i];

}

  

  

for(int i=0;i<size;i++)

B[i] = A[i];

  

for(int i=0;i<size;i++)

{

index = 2*i;

if(index>=size)

break;

else

swap(B[i],B[index]);

  

}

  

for(int i=0;i<size;i++)

C[i] = B[i]+A[i];

  

int half = size%2==0?size/2:(size+1)/2;

  

int minimum = 0;

  

for(int i=0;i<half;i++)

{

if(i==0)

minimum = C[0];

else

{

if(C[i]<minimum)

minimum = C[i];

}

}

  

cout << "Elements of Array A is : ";

for(int i=0;i<size;i++)

cout << A[i] << " ";

cout << endl;

  

cout << "Elements of Array B is : ";

for(int i=0;i<size;i++)

cout << B[i] << " ";

cout << endl;

  

cout << "Elements of Array C is : ";

for(int i=0;i<size;i++)

cout << C[i] << " ";

cout << endl;

  

cout << "Minimum element in half of the array is : " << minimum << endl;

return 0;

}

OP:

Input the size of array : 10

Input number 1 : 4

Input number 2 : 5

Input number 3 : 8

Input number 4 : 12

Input number 5 : 34

Input number 6 : 56

Input number 7 : 1

Input number 8 : 0

Input number 9 : 22

Input number 10 : 7

Elements of Array A is : 4 5 8 12 34 56 1 0 22 7

Elements of Array B is : 4 8 34 1 22 56 12 0 5 7

Elements of Array C is : 8 13 42 13 56 112 13 0 27 14

Minimum element in half of the array is : 8