Thursday, July 30, 2009

C++ sorce code for user input matrix size & values during runtime and rotate 90 degrees clockwise?

I'm having problems rotating 90 degrees clockwise for a matrix with user inputing size %26amp; values during runtime and rotation is performed in function. How to pass matrix to function %26amp; use pointers for this problem?





Here's the question.





Write %26amp; rtest the function that rotate 90 degrees clockwise a two-dimensional square array of ints. For example, it would transform the array





11 22 33


44 55 66


77 88 99





to





77 44 11


88 55 22


99 66 33





The program should use dynamic memory allocation to allocate memory for the 2D array after getting the size of the square array.





It's hard to rotate when having the user giving array size and rotate based on the size.





Please insert the C++ source code for this question.





All helps are appreciated.TQ very much.

C++ sorce code for user input matrix size %26amp; values during runtime and rotate 90 degrees clockwise?
To use pointer with 2D matrix it is better to use pointer to a pointer. It can be used like usual 2D array.


Code in main should be something like below


//input dimension from user, m by n matrix


int** matrix;


matrix=new int*[m];


for( i=0;i%26lt;m;i++)


matrix[i]=new int[n];


// now input matrix from user in usual way.





now you can use this pointer to pointer as usual 2D array, when calling function just pass pointer to pointer as argument.


I have said you how to raotate 2D array in your previous question. I'm just repeating procedures, not the code.


First transpose the matrix and then reflect it wrt horizontal axis. I think this will work.
Reply:Run it u can get some idea ...





#include%26lt;stdio.h%26gt;


#include%26lt;conio.h%26gt;





#include%26lt;stdlib.h%26gt;





# define ROW 4


# define COL 4





void rotate_90(int**,int,int);


void print_matrix(int* m , int r, int c );











int main()


{


int * matrix ;


matrix= (int*)malloc(COL*ROW*sizeof(int));


int count=0;





for(int i=0;i%26lt;ROW;i++)


for(int j=0;j%26lt;COL;j++)


matrix[i*COL+j]=count++;


printf("till ");





print_matrix(matrix,ROW,COL);


rotate_90(%26amp;matrix,ROW,COL);





printf("\n\n");





print_matrix(matrix,COL,ROW);








return 0;


}








void rotate_90(int** m,int r,int c)


{


int *matrix;


matrix=(int*)malloc(r*c*sizeof(int));


for(int i=0;i%26lt;r;i++)


for(int j=0;j%26lt;c;j++)


matrix[j*c + c-i-1]=(*m)[i*c+j];





free(*m);


*m=matrix;











}





void print_matrix(int* m , int r, int c )


{


int j=0;


for(int i=0;i%26lt;r;i++)


{printf("\n");


for(int j=0;j%26lt;c;j++)


{


printf("%d \t",m[i*c+j]);


}


}


}


No comments:

Post a Comment