create 2d array based on user input
Sep 5, 2015 at 11:25am UTC
thanks done
Last edited on Sep 8, 2015 at 6:32pm UTC
Sep 5, 2015 at 2:19pm UTC
You cannot input a constant value, for a constant value cannot be changed and must always be initialized in the code.
What you need to do, since the size isn't a constant value, is to dynamically allocate memory for your array. Doing this with a 1D array is easier:
int *arr = new int [size]
. With a 2D array, you do the following:
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 45 46 47 48 49 50
#include <iostream>
int main()
{
unsigned int rows = 0, cols = 0;
std::cout << "Rows: " ;
std::cin >> rows;
std::cout << "Columns: " ;
std::cin >> cols;
//Dynamically allocate memory for the array
int **arr = new int *[rows];
for (unsigned int i = 0; i < rows; i++)
{
arr[i] = new int [cols];
}
///////////////////////////////////////////////////
//You can use the array here like you normally would
for (unsigned int i = 0; i < rows; i++)
{
for (unsigned int j = 0; j < cols; j++)
{
std::cout << "arr[" << i + 1 << "][" << j + 1 << "]=" ;
std::cin >> arr[i][j];
}
}
std::cout << "\nThe array you entered:\n" ;
for (unsigned int i = 0; i < rows; i++)
{
for (unsigned int j = 0; j < cols; j++)
{
std::cout << arr[i][j] << " " ;
}
std::cout << "\n" ;
}
/////////////////////////////////////////////////
//Deallocate the memory after you're done using it
for (unsigned int i = 0; i < rows; i++)
{
delete [] arr[i];
}
delete [] arr;
std::cin.ignore();
std::cin.get();
return 0;
}
Last edited on Sep 5, 2015 at 2:23pm UTC
Sep 5, 2015 at 4:35pm UTC
@Tommy98 , make sure to read about difference between arrays and dynamic arrays .
Sep 5, 2015 at 10:39pm UTC
Must it be arrays? Why not a vector?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main()
{
typedef vector <double > row_type;
typedef vector <row_type> matrix_type;
matrix_type m;
unsigned rows, cols;
std::cin >> rows >> cols;
for (unsigned r = 0; r < rows; r++)
{
row_type row;
std::copy_n( std::istream_iterator <double > ( std::cin ), cols, std::back_inserter( row ) );
m.emplace_back( row );
}
}
Last edited on Sep 5, 2015 at 10:40pm UTC
Topic archived. No new replies allowed.