c++ Dynamic 1-D array Create three dynamically allocated arrays (x, y, and z) of
ID: 3861867 • Letter: C
Question
c++
Dynamic 1-D array Create three dynamically allocated arrays (x, y, and z) of size N, where N is a number entered by the user. Populate x with even numbers and y with odd number. Add the respective element in x to the respective element in y, and store the result in the respective element in z using the following function, void sum_elements(int x[], int y[], int z[], int size).
Static 2-D array Create a 3 x 3 array, and assign 1s to all columns in the first row, 2s to all columns in the second row, and 3s to all columns in the third row. Sum all the elements in the array, and return the sum as an integer using the following function, int sum_elements(int x[][3]).
please explain each step/ why you wrote the code as such
Explanation / Answer
#include <iostream>
using namespace std;
void sum_elements(int x[], int y[], int z[], int size) //function definition
{
int i;
for(i=0;i<size;i++)
{
z[i] = x[i] + y[i];
}
}
int main()
{
int i,size;
int even = 2;
int odd = 1;
cout<<"Enter the number of elements in the array";
cin>>size;
//dynamic allocation using new
int *x = new int[size];
int *y = new int[size];
int *z = new int[size];
for(i=0;i<size;i++)
{
x[i] = even; // x array contains even numbers upto size
even = even +2;
}
for(i=0;i<size;i++)
{
y[i] = odd; // y array contains odd numbers upto size
odd = odd +2;
}
sum_elements(x,y,z,size); //call to function
cout<<endl;
for(i=0;i<size;i++)
{
cout<<x[i]<<" ";
}
cout<<endl;
for(i=0;i<size;i++)
{
cout<<y[i]<<" ";
}
cout<<endl;
for(i=0;i<size;i++)
{
cout<<z[i]<<" ";
}
delete [] x; // deallocate memory
delete [] y;
delete [] z;
return 0;
}
Output:
Enter the number of elements in the array 10
2 4 6 8 10 12 14 16 18 20
1 3 5 7 9 11 13 15 17 19
3 7 11 15 19 23 27 31 35 39
#include <iostream>
using namespace std;
int sum_elements(int x[][3])
{
int sum = 0;
int i,j;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
sum = sum + x[i][j]; // sum all elements of array
}
}
return sum; //return sum
}
int main()
{
static int array[3][3] = {{1,1,1},{2,2,2},{3,3,3}}; //static array
int i,j;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
cout<<array[i][j]<<" "; //display all elements of array
}
cout<<endl;
}
cout<<" Sum of elements : "<<sum_elements(array); //call function
return 0;
}
Output:
1 1 1
2 2 2
3 3 3
Sum of elements : 18
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.