i need to create ad 2d dynamic array and then create a function that will receive the 2d dynamic array and then rotate it 90 degrees clockwise and return it back to main. However i am not sure why i am not getting any output? is it because of the wrong swapping technique? i figured that the indices swapping is as follows:
I J-----------I J
0 0 0 1
0 1 1 1
0 2 2 1
with that i came with :
for (int i = 0; i <row;i++)
for(int j = 0;j<col; j++)
{
Roti[i+j][row-i]=arr[i][j];
}
Code:
#include <iostream>
using namespace std;
void print2DArray(int **arr, int rows, int cols);
int **Rotate(int **arr, int row, int col)
{
int **Roti = new int *[row];
for (int i = 0; i <row;i++)
{
Roti[i] = new int [col];
}
for (int i = 0; i <row;i++)
for(int j = 0;j<col; j++)
{
Roti[i+j][row-i]=arr[i][j];
}
return Roti;
}
int main()
{
int *A[3];
for (int i = 0; i < 3; i++)
{
A[i] = new int[3];
for (int j = 0; j < 3; j++)
{
A[i][j] = rand() % 20;
}
}
cout << "The array is :\n";
print2DArray(A, 3, 3);
int **ptr;
ptr=Rotate(A,3,3);
cout<<"-----"<<endl;
print2DArray(ptr, 3, 3);
for (int i = 0; i < 3; i++)
{
delete[] A[i];
}
return 0;
}
void print2DArray(int **arr, int rows, int cols)
{
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
cout << arr[i][j] << " ";
}
cout << endl;
}
}