In: Computer Science
write this program in c++ using iostream library.( cin>>n; cin>> arr[n] and so on)
Write a function that converts an array so that in the first half settled with elements from odd positions, and in the second half - with elements from the even positions.Positions are counted from the first index.The program have to use pointer.
example: input:
7
1 2 3 4 5 6 7
output: 1 3 5 7 2 4 6 8
Program
#include <iostream>
using namespace std;
/* converts an array so that in the first half settled with elements from odd positions, and in the second half - with elements from the even positions */
void convert(int *a, int n)
{
int k = 0, j, t;
for(int i=0; i<n/2-1; i++)
{
k += 2;
t = *(a+k);
for(j=k-1; j>=i+1; j--)
{
*(a+j+1) = *(a+j);
}
*(a+j+1) = t;
}
}
//main function
int main()
{
int n;
cout<<"Enter n:";
cin >> n;
int *a = new int[n];
cout<<"Enter the array elements: "<<endl;
for(int i=0;i<n; i++)
{
cin >> *(a+i);
}
convert(a, n);
cout<<"Converted array:"<<endl;
for(int i=0;i<n; i++)
{
cout << *(a+i) << " ";
}
return 0;
}
Output:
Enter n:8
Enter the array elements:
1 2 3 4 5 6 7 8
Converted array:
1 3 5 7 2 4 6 8
Enter n:7
Enter the array elements:
1 2 3 4 5 6 7
Converted array:
1 3 5 2 4 6 7
Note: Your feedback is very important for us, I expect
positive feedback from your end.