Question

Question 1: Fix the 2D dynamic array initialization in following code #include <iostream> using namespace std;...

Question 1:

Fix the 2D dynamic array initialization in following code

#include <iostream>

using namespace std;


int main(){
  
int rows = 5;
int cols = 5;
int x;
  
int** arr = new int[rows][cols]
  
cin >> x;
arr[x][x] = x;
cout << "arr[x][x] = " << arr[x][x];
  
return 0;
}

Question 2:

Fix the code to initialize the 2D array elements to x

#include <iostream>

using namespace std;


int main(){
  
int rows;
int cols;
int x;
  
cin >> rows;
cin >> cols;
cin >> x;
  
int** arr = new int*[rows];
for(int i = 0; i < rows; ++i)
arr[i] = new int[cols];
  
// initialization, your code goes here

  
  
for(int i = 0; i < 3; i++){ // prints some values in the array
for(int j = 0; j < 3; j++)
cout << arr[i][j];
cout <<"\n";
}
  
return 0;
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

CodeToCopy:

Question 1:

2darray_init.cpp

#include <iostream>

using namespace std;

int main(){

    int rows = 5;

    int cols = 5;

    int x;

    /* allocating memory for rows */

    int** arr = new int*[rows];

    /* allocating memory for columns */

    for (int i = 0; i < rows; ++i ) {

        arr[i] = new int[cols];

    }

    /* taking x from user */

    cin >> x;

   

    /* place x at x'th row, x'th column */

    arr[x][x] = x;

   

    /* printing x'th row, x'th column value */

    cout << "arr[x][x] = " << arr[x][x] << endl;

    return 0;

}

Question 2:

2darray_init2.cpp

#include <iostream>

using namespace std;

int main(){

    int rows;

    int cols;

    int x;

     

    cin >> rows;

    cin >> cols;

    cin >> x;

     

    int** arr = new int*[rows];

    for(int i = 0; i < rows; ++i) {

        arr[i] = new int[cols];

       

        /* assigning x value to 2d array elements */

        for (int j = 0; j < cols; ++j) {

            arr[i][j] = x;

        }

    }

     

    for(int i = 0; i < 3; i++){ // prints some values in the array

        for(int j = 0; j < 3; j++)

            cout << arr[i][j] << " ";

        cout <<"\n";

    }

     

    return 0;

}

OutputScreenshot:


Add a comment
Know the answer?
Add Answer to:
Question 1: Fix the 2D dynamic array initialization in following code #include <iostream> using namespace std;...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT