Skip to main content

Posts

Showing posts from September, 2007

Some Operations on Matrix

A few days back someone asked me a question via email which I thought might be useful to others too. So I’m listing that question along with its answer below. Q. I want to write a program such that users enter the value of matrix and each operation (listed below) is performed by functions. I want to use switch structure to call the functions. 1. Rotate the matrix around the diagonal. Example: 1 2 3 ---> 1 4 7 4 5 6 2 5 8 7 8 9 3 6 9 2. Rotate the matrix around the middle row. Example: 1 2 3 ---> 7 8 9 4 5 6 4 5 6 7 8 9 1 2 3 3. Rotate the matrix around the middle column. Example: 1 2 3 ---> 3 2 1 4 5 6 6 5 4 7 8 9 9 8 7 4. Set the upper triangle to zero. Example: 1 2 3 ---> 1 0 0 4 5 6 4 5 0 7 8 9 7 8 9 Ans. The following program does it. Please note that the matrix is declared as global so as to reduce complications in the program. Better way should have been to pas

Overloading [] Operator II

In the previous article Overloading [] Operator , we overloaded the [] operator in a class to access data within the class by indexing method. The operator [] function was defined as below: int myclass:: operator []( int index) { // if not out of bound if (index<num) return a[index]; } As you can see, the above operator function is returning values, hence it could only be used on the right hand side of a statement. It’s a limitation! You very well know that a statement like below is very common with respect to arrays: a[1]=10; But as I said, the way we overloaded the [] operator, statement like the one above is not possible. The good news is, it is very easy to achieve this. For this we need to overload the [] operator like this: int &myclass:: operator []( int index) { // if not out of bound if (index<num) return a[index]; } By returning a reference to the particular element, it is possible to