c++ Dynamic 1-D array Create three dynamically allocated arrays (x, y, and z) of
ID: 3861369 • 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>
#include <new>
using namespace std;
void sum_elements(int x[], int y[], int z[], int size);
int main ()
{
int i,n;
int x[50];
int y[50];
int z[50];
cout << "what is the array size? ";
cin >> n;
for (i=0; i<n; i++)
{
cout << "Enter an even number: ";
cin >> x[i];
cout << "Enter an odd number: ";
cin >> y[i];
}
cout << "You have entered: ";
for (i=0; i<n; i++)
cout << x[i] << ", ";
for (i=0; i<n; i++)
cout << y[i] << ", ";
sum_elements(x,y,z,n);
return 0;
}
void sum_elements(int x[], int y[], int z[], int size)
{
int j;
for (j=0; j<size; j++)
{
z[j]=x[j]+y[j];
}
cout << "sum of corresponding element in x to corresponding element in y is: ";
for (j=0; j<size; j++)
cout << z[j] << ", ";
}
sum of all elements in a station 3*3 array is as follows:
#include <iostream>
using namespace std;
int main()
{
int x[3][3] = {
{0, 0, 0},
{1, 1, 1},
{2, 2, 2}
};
for ( int i = 0; i < 3; i++ )
for ( int j = 0; j < 3; j++ ) {
cout << "x[" << i << "][" << j << "]: ";
cout << x[i][j]<< endl;
}
cout << "sum of array elements is: "<< sum_elements(x)<<endl;
return 0;
}
int sum_elements(int x[][3])
{
int sum=0;
for ( int i = 0; i < 3; i++ )
for ( int j = 0; j < 3; j++ ) {
sum=sum+x[i][j];
return sum;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.