All code must be in C++ using G++ compiler Write a function that accepts an int
ID: 3819861 • Letter: A
Question
All code must be in C++ using G++ compiler
Write a function that accepts an int array and the array's size as arguments. The function should create a new array, using dynamic memory allocation, that is of the same size as the argument array. The argument array's size is user defined in the main() function. Now, using pointers to both the arrays, first copy the elements at odd positions (1st, 3rd, 5th), and next copy the elements at even positions (2nd, 4th, 6th) from the argument array to the dynamically allocated array. Finally, in the same function, print the contents of the argument array and the newly created array.Explanation / Answer
#include<iostream>
using namespace std;
void oddeven(int a[],int s)
{
// dynamic array b is created by using dynamic memmory allocation/new keyword.
int* b=new int[s];
// counter taken for array b
int c=0;
// elements at odd positions
for(int i=0;i<s;i++)
{
//odd elements as index starts from zero
if(i%2==0)
{
b[c]=a[i];
c++;
}
}
// elements at even position
for(int i=0;i<s;i++)
{
//even elements as index starts from zero
if(i%2==1)
{
b[c]=a[i];
c++;
}
}
// elements of both arrays are printed as stated
cout<<"Elements of the original array are ";
for(int i=0;i<s;i++)
{
cout<<" "<<a[i]<<" ";
}
cout<<"Elements of the Dynamically created array are ";
for(int i=0;i<s;i++)
{
cout<<" "<<b[i]<<" ";
}
}
int main()
{
// intger input array taken or we can take array from user as input
int a[]={1,4,6,99,11,33,55,60,45,72};
//size of the entered array calculated as integer takes 4 bytes we have divided size by 4.
int s=sizeof(a)/4;
cout<<"Size of S is "<<s<<" ";
//function called and input parameters are array a and its size
oddeven(a,s);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.