Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

In C++, create a two-dimensional array that is capable of storing integers and i

ID: 641970 • Letter: I

Question

In C++, create a two-dimensional array that is capable of storing integers and initialize each entry to O. The array can have any number of rows and columns, but make it a good size to display on the screen Create a function that prints the array to the screen as a table with the appropriate rows and column& Use setw() to ensure the numbers have enough room- You may assume the numbers are no more than 3 digits each Include the row and column labels In main, ask the user to supply a row and column and a value (no more than 3 digits), then put the value into the array at that row and column. Print the result and ask the user for another row, column and value. Repeat until the user is finished. Once finished, compute and print the total of the values in the array.

Explanation / Answer

#include <iostream>
#include <iomanip>

using namespace std;

int main(){
   int rows, cols;
   cout << "Number of rows: ";
   cin >> rows;
   cout << "Number of cols: ";
   cin >> cols;
   int **arr = new int*[rows];
   for(int i = 0; i < rows; ++i){
       arr[i] = new int[cols];
       for(int j = 0; j < cols; ++j){
           arr[i][j] = 0;
       }
   }
   int r, c, val, sum = 0;
   while(true){
       cout << "Enter row number, col number: ";
       cin >> r >> c;
       if((r < rows && r >= 0) && (c < cols && c >= 0)){
           arr[r][c] = val;
           cout << "Enter negative value to exit" << endl;
           cout << "Enter a value to store at " << r << ", " << c << ": ";
           cin >> val;
           if(val < 0){
               break;
           }
       }
       else{
           cout << "Invalid indexes" << endl;
       }
   }
   for(int i = 0; i < rows; ++i){
       for(int j = 0; j < cols; ++j){
           sum += arr[i][j];
       }
   }
   cout << "Sum of all values is " << sum << endl;
   return 0;
}