user input into 2d array
Jul 20, 2014 at 9:51pm UTC
Wondering how to get a users input to store into a 2d array. am I even close?
Also I was wondering about how to get the array to display as a table once I get data into it.
Thanks.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
const int ROWS = 4;
const int COLS = 4;
int showArray (int [ROWS][COLS]);
int main()
{
int table1;
table1 = showArray(int [ROWS][COLS]);
cout << table1;
return 0;
}
int showArray( int [ROWS][COLS])
{
int x = 0;
int y = 0;
int userInput;
int array[ROWS][COLS];
for (int y =0; y<ROWS; y++)
{
for (int x =0; x<COLS; x++)
{
cout << "Enter Row of Data" ;
cin >> userInput;
array[x][y]= userInput;
}
}
return array[x][y];
}
Jul 20, 2014 at 11:20pm UTC
Hey, your functions "showArray" does not show any array. Instead it fills and array. There would have been 2 functions "fillArray" and "showArray".
Also, your main is totally messed up
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
#include <iostream>
#include <iomanip>
using namespace std;
void fillArray(int **array,int row,int col)
{
int i,j;
cout<<"Enter Data in array" <<endl;
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
cout<<"Enter element [" <<i<<"][" <<j<<"]: " ;
cin>>array[i][j];
}
}
}
void showArray(int **array,int row,int col)
{
int i,j;
cout<<"Table of contents" <<endl;
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
cout<<setw(3)<<array[i][j]; //show row in one line
}
cout<<endl;
}
}
int main()
{
int row,col;
cout<<"Enter row: " ;
cin>>row;
cout<<"Enter col: " ;
cin>>col;
int array[row][col]; //declare array
fillArray(array,row,col);
showArray(array,row,col);
return 0;
}
Jul 20, 2014 at 11:20pm UTC
you could just put input straight into the array instead of using another variable.
Topic archived. No new replies allowed.