I have learnt a program to create number of arrays according to the user input.
But now I want the situation for creating arrays for matrices (2D) to save the elements of the matrices.
User should enter the number of matrices he want and the size of each individual matrix and enter the respective numbers.
Can anyone please help me out with this.
Here is the normal code which I studied. I want it to be usable for matrices.**
#include <iostream>
int main()
{
unsigned int n;
std::cout << "Enter number of arrays: ";
std::cin >> n;
double** array = new double*[n];
unsigned int* sizeOfInnerArrays = new unsigned int[n];
for (int i = 0; i < n; ++i)
{
std::cout << "Enter size of array " << i << ": ";
std::cin >> sizeOfInnerArrays[i];
array[i] = new double[sizeOfInnerArrays[i]];
for (int j = 0; j < sizeOfInnerArrays[i]; ++j)
{
int element;
std::cout << "Enter element " << j << " of array " << i << ": ";
std::cin >> element;
array[i][j] = element;
}
}
//prints out each array as curly-brace enclosed sets of doubles
for (int i = 0; i < n; ++i)
{
std::cout << "{";
for (int j = 0; j < sizeOfInnerArrays[i] - 1; ++j)
{
std::cout << array[i][j] << ", ";
}
std::cout << array[i][sizeOfInnerArrays[i] - 1] << "}" << std::endl;
}
// free dynamically allocated memory
for (int i = 0; i < n; ++i)
{
delete [] array[i];
}
delete[] array;
delete[] sizeOfInnerArrays;
#include <iostream>
#include <vector>
int main()
{
std::size_t n ;
std::cout << "number of arrays: " ;
std::cin >> n ;
// https://cal-linux.com/tutorials/vectors.html
std::vector< std::vector<double> > array(n) ; // array of 'n' arrays
for( std::size_t i = 0 ; i < n ; ++i )
{
std::size_t m ;
std::cout << "size of inner array " << i << ": " ;
std::cin >> m ;
array[i].resize(m) ; // resize to array of 'm' double values
// accept the value of each item in this inner array
// http://www.stroustrup.com/C++11FAQ.html#forfor( double& v : array[i] ) // for each item v in the inner array
std::cout << "element: " && std::cin >> v ;
}
// print out each array as curly-brace enclosed sets of doubles
// http://www.stroustrup.com/C++11FAQ.html#autofor( constauto& inner_array : array ) // for each inner array
{
std::cout << "{ " ;
for( double v : inner_array ) // for each value in the inner array
std::cout << v << ' ' ;
std::cout << "}\n" ;
}
}