In: Computer Science
In C++, create a 3-by-3 array that is capable of storing integers and initialize each entry to 0. Ask the user to supply a row and a column and a value, then put the value into the array at that row and column. Print the array to the screen as a table with 3 rows and 3 columns, and ask the user for another row, column, and value. Repeat until user inputs values for all entries.
Once finished, compute and print the total of the values in the array.
1. When the array is printed to the screen as a table, use setw() to ensure the numbers have enough room. You may assume the numbers are no more than 3 digits each.
2. Your program needs to check whether the user input row and column are valid. If the user inputs an invalid row or column (i.e. less than 1 or greater than 3), prompt the user to re-input valid row and column.
3. If an entry already has a user input, your program should disallow user to input a value at the same entry and also ask user to enter a value at a different entry.
Please follow all the comments in the code for a better understanding
#include <iostream>
#include <iomanip>
using namespace std;
//function return 1 if array contains 0 because the input prompt coninues when array has 0's
int check(int arr[3][3]){
int i,j;
for(i=0;i<3;i++)
for(j=0;j<3;j++)
if(arr[i][j]==0)
return 1;//input process to be continued
return 0;//input process to be stopped
}
//fuction returns 1 if value inserted successfully
int setValue(int i,int j,int val,int arr[3][3]){
if(arr[i][j]!=0)
return 0;//already assigned
arr[i][j]= val;
return 1;
}
//print the array elements
void print(int arr[3][3]){
int i,j;
//setw sets offset sapce between elements
cout<<setw(3);
for(i=0;i<3;i++){
for(j=0;j<3;j++){
cout<<arr[i][j]<<setw(3);
}
cout<<endl;
}
}
int main()
{
int arr[3][3];
int i,j,k;
//initialize all values with zeroes in arr
for(i=0;i<3;i++)
for(j=0;j<3;j++)
arr[i][j]=0;
// continuosly prompt for input until array doesnt contain 0's
while(check(arr)){
//read input values
int row,col,val;
cout<<"Row Col value\n";
cin>>row>>col>>val;
//if row and columns values are invalid
if(row>=0 && row<3 && col>=0 && col<3)
//check value Already inserted in given position
if(setValue(row,col,val,arr))
continue;
else
cout<<"Already value assigned !! Try inserting in another position";
else
cout<<"Enter valid position";
}
//print the array
print(arr);
return 0;
}
Output
feel free to ask doubts in the comment section so that I can modify the answer according to your need
thank you
please support by giving a thumbs up.