IN C++ Given the array inputArray (doubles), write a function called swap which
ID: 3684729 • Letter: I
Question
IN C++
Given the array inputArray (doubles), write a function called swap which will swap any two contiguous (next to each other) elements. Swap will be passed two parameters, the first element to be swapped and the array name. Write another function printArray that will print the array. PrintArray will be passed two parameters the array name and the array size. You many hardcode the array into the problem. The array elements are: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10. Run the program three times: Print the array, swap elements 4 and 5 and print the array again. Print the array, swap elements 8 and 9 and print the array again. Print the array, swap elements 1 and 2 and print the array again.
Explanation / Answer
#include <iostream>
using namespace std;
void swap(double arr[], double firstElement){
int i=0;
for(int i=0;i<9;i++){
if(arr[i]==firstElement){
double temp=firstElement;
arr[i]=arr[i+1];
arr[i+1]=temp;
break;
}
}
}
void printArray(double arr[], int size){
int i=0;
for(i=0;i<size;++i)
cout<<arr[i]<<" ";
cout<<endl;
}
int main(){
double inputArray[]={1,2,3,4,5,6,7,8,9,10};
int i=0;
for(i=0;i<3;++i){
printArray(inputArray,10);
if(i==0)
swap(inputArray,3);
else if(i==1)
swap(inputArray,8);
else if(i==2)
swap(inputArray,1);
printArray(inputArray,10);
}
return 0;
}