Pages

Thursday, July 11, 2013

Matrix problem of Classes in C++

/*
QUESTION:
A matrix is a two dimensional array. Create a class ‘matrix’ that contains two attributes

max_x and max_y of type int, that stores size of maximum columns and rows respectively. Add

another attribute of type int** to store the array.

Constructor should allow the program to specify the actual dimensions of the matrix and store it

to max_x and max_y, and define a two dimension array of the given size.

Member functions that access the data in the matrix will needed two index numbers: one for

each dimension in array.

Here what a fragment of main() program that operate on such class looks like:

matrix m1(3,4) // define a matrix object

int temp=1234; //define an int value

m1.putel(7,4,temp) //insert value of temp into matrix at 7,4 location,

//return true if temp is inserted and false if this location is out of bound

Temp=m1.gettel(7,4) // retrun value from matrix at 7,4 and display message if this given index

is out of bound.
 


CODE;
*/

#include <iostream>
using namespace std;

class matrix{
private:
int max_x;
int max_y;
    int **ptr;
    
public:
matrix(){
max_x=0;
max_y=0;
ptr = NULL;
}
matrix(int x,int y){
max_x = x;
max_y = y;
ptr = new int *[max_x];
for(int i=0;i<max_x;i++)
ptr[i]= new int[max_y];
}
    bool putel(int  x,int y,int temp){
if(x  >max_x || y >max_y){
cout<<"\nOut of Bound: ";
return 0;
}
else{
ptr[x][y]= temp;
return 1;
}
}
int gettel(int x,int y){
if(x>max_x || y >max_y){
cout<<"\nOut of Bound: ";
return 0;
}
else 
return ptr[x][y];
}
};

int main(){
matrix m1(8,4);
int temp=1234;
m1.putel(4,4,temp);
temp = m1.gettel(4,4);
cout<<endl<<temp<<endl;
return 0;
}

No comments:

Post a Comment