In C Given two arrays A and B The 2D array A has eight eleme
In C++, Given two arrays A and B. The 2D array A has eight elements, copy them to array B according to their value. For example, put element with value 0 to B[0], put element with value 1 to B[1], and so on. You can use either for-loops or while-loops, but you must use a nested loop to complete this program.
The output of this program is:
The content of B is
0 1 2 3 4 5 6 7
#include <iostream>
using namespace std;
void main() {
int A[2][4] = {{2, 10, 3, 5},{4, 2, 6, 4}};
int B[8];
// add your code here
cout << \"The content of B is\" << endl;
for (int y=0; y<8; y++) {
cout << B[y] << \" \";
}
cout << endl;
}
Solution
#include <iostream>
using namespace std;
int main() {
int i,j;
int A[2][4] = {{0, 2, 3, 4},{1, 7, 6, 5}}; // define A array with 8 elements
int B[8];
for(i=0;i<2;i++){ // loop in rows
for(j=0;j<4;j++){ // loop in columns
int x = A[i][j]; // get ith row jth column element in A
B[x] = x; // store the value in its index.
}
}
cout << \"The content of B is\" << endl;
for (int y=0; y<8; y++) {
cout << B[y] << \" \";
}
cout << endl;
}
/*sample output
*/

