• Register

Sometimes in life, you may wanna convert a matrix into a one dimensional array for the sake of the simplicity or maybe some other causes.

And here’s when this article will come in handy.

Attached within this article is the function needed to convert a 2D array into a 1D one, by implementing both, the actual function and the main function.

#include <iostream>
using namespace std;
void convert(int** A, int* V, int n, int m) {    //The usage of * is to remove the need of providing the size of the array, which makes it 
// more dynamic
// A is the original 2D array, V the new array, n the rows and m the columns

	int k = 0;       //k is the counter of elements, used as an index to store all the elements of A in V.

	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			V[k] = A[i][j];
			k++;
		}
	}

}

void main() {

	int n, m;

	do {
		cout << "Enter n: ";
		cin >> n;
	} while (n <= 0);   //To avoid using a negative number as number of rows

	do {
		cout << "Enter m: ";
		cin >> m;
	} while (m <= 0);   //To avoid using a negative number as number of columns

	int** A = new int* [n]; //Dynamically allocate n rows

	for (int i = 0; i < n; i++)
		A[i] = new int[m];  //To dynamically allocate m columns

	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			cout << " \n Enter the element: [" << i << "][" << j << "] ";
			cin >> A[i][j];
		}
	}

			int* V = new int[n * m];  //n*m because there are n*m elements in the matrix A

			convert(A, V, n, m);

			cout << " \n The array V now contains: \n";
			for (int i = 0; i < n * m; i++)
				cout << V[i] << " " ;

		}

 

100 points
3