xxxxxxxxxx
/*
Type of 2D Array Declaration
Type-1 : General Way
Type-2 : Using Single Pointer
Type-3 : Using Double Pointer
The program will take user input for each type and will print the 2d array
*/
#include<iostream>
using namespace std;
//Method 1- General Way
void Simple2DArray(int row, int col){
int arr[row][col];
for(int i=0; i<row; i++){
for(int j=0; j<col; j++){
cout << "Enter element of row " << (i+1) << " column " << (j+1) << " : " << endl;
cin >> arr[i][j];
}
}
for(int i=0; i<row; i++){
for(int j=0; j<col; j++){
cout << arr[i][j] << " ";
}
cout << endl;
}
}
//Method 2- Using single pointer
void SinglePointer2DArray(int row, int col){
int *arr[row];
for(int i=0; i<row; i++){
arr[i] = new int[col];
}
for(int i=0; i<row; i++){
for(int j=0; j<col; j++){
cout << "Enter element of row " << (i+1) << " column " << (j+1) << " : " << endl;
cin >> arr[i][j];
}
}
for(int i=0; i<row; i++){
for(int j=0; j<col; j++){
cout << arr[i][j] << " ";
}
cout << endl;
}
}
//Method 1- Using double Pointer
void DoublePointer2DArray(int row, int col){
int **arr;
arr = new int *[row];
for(int i=0; i<row; i++){
arr[i] = new int[col];
}
for(int i=0; i<row; i++){
for(int j=0; j<col; j++){
cout << "Enter element of row " << (i+1) << " column " << (j+1) << " : " << endl;
cin >> arr[i][j];
}
}
for(int i=0; i<row; i++){
for(int j=0; j<col; j++){
cout << arr[i][j] << " ";
}
cout << endl;
}
}
int main(){
int row, col;
cout << "Enter Number Of Rows: ";
cin >> row;
cout << endl << "Enter Number Of Columns: ";
cin >> col;
DoublePointer2DArray(row,col);
return 0;
}
xxxxxxxxxx
int row,col;
cout << "please input how many rows and columns you want accordingly: ";
cin>>row>>col;
//create array in heap.
int **arr=new int*[row];
for(int i=0;i<row;i++)
{
arr[i]=new int[col];
}
//getting value from user.
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
cout<<"Enter a number ";
cin>>arr[i][j];
}
}
//display Elements.
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
cout<<arr[i][j]<<" ";
}
}
return 0;
xxxxxxxxxx
//* 2D arrays
int n, m;
cout << "Enter row and column: ";
cin >> n >> m;
int arr[n][m];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cin >> arr[i][j];
}
}
cout << "\nShowing array\n";
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cout << arr[i][j] << " ";
}
cout << endl;
}