Thursday, June 4, 2015

A beginner's code in Java to illustrate the concept of Inheritance

Java is an object oriented programming language, which implies that whilst coding in java, you need to model your problems in the form of an emulation or a blue print of the real world objects. And for that purpose you need to use class. A class can be thought of as a blueprint of a real world entity.

E.g. Let's take a student. A student has a conceptual existence, right? Yes, because it has some attributes that help us identify it, per say, a name, a Roll number, Class, Marks etc. And a student must do somethings also, like acquire values to these attributes, such as "Mark", for a name. And the ability to tell others about the values that it's attributes carry, that makes him/her unique.

So, if we are to implement this student class, this is the syntax that we need to follow.

A declaration of class follows this syntax :

class <class_name>
{
       <accessibility_mode> <return_type> <attribute_name>;
/*the accessibility modes such as private, protected, public, default are used to define the scope of visibility of the members of the class to the other elements of the program. Just like we as humans have personal space, and personal interests, which are not to be shared with others, so do the classes.
Usually, in a class, the data members are kept private, i.e invisible to other elements whereas the member functions or member methods are public, that is, they interact directly with the external elements*/
       ..................................................
       ..................................................
       <accessibility_mode> <return_type> <function_name> ( )
       {
              ................................
       }
}


Now let's jump straight to it's implementation using a code that creates a console application to store the marks of five students and display them according to the grade that they obtained like failed, passed, scored more than 60% marks. The code follows:

package student;

import java.util.*;                                      

/*This statement lets us call on some predefined classes, their objects and their methods so as to make use them. from the java.util package, we call on the package Scanner to take user based inputs, whilst the run of the programs */ 

class std
{
    private int rno;
    private String name;
    private long per;
    private int[ ] marks = new int[5];
 
    public int cal_marks( )
    {
        int sum = 0;
        for(int i = 0; i < 5; i++)
            sum += marks[i];
        return sum;
    }
 
    public void cal_per(int sum)
    {
        per = sum/5;
    }

    public long give_per( )
    {
        return per;
    }
 
    public void getinfo( )
    {
        Scanner in = new Scanner(System.in);
/*Scanner is a class defined in java.util that has methods such as nextInt( ), next( ) etc. that helps us take user based inputs. We declare an object in of scanner and we initialize with the         parameter System.in, which is java's input stream*/
        System.out.print("\nEnter the Roll No. :\t");
        rno = in.nextInt( );
        System.out.print("\nEnter the Name of the student : \t");
        name = in.next( );
        System.out.print("\nEnter the marks of the 5 subjects. Hit Return after entering a field:\n");
        for(int i = 0; i < 5; i++)
            marks[i] = in.nextInt( );
            cal_per(cal_marks( ));
    }
 
    public void showinfo( )
    {
        System.out.print("\n"+rno+"\t"+name+"\t"+per);
    }
}

/*OOP is all about extensibility and reusability. That is why in OOP we can inherit the data members and member methods of existing classes, so as we do not need to write the same code again. Now the class which is inheriting from another class is called the derived class and the class which is being inherited is called the base class. The syntax is like this :

class <derived_class_name> extends <base_class_name>. the keyword extends illustrates inheritance */ 

class res extends std    
{
    public Boolean ifpass( )
    {
      if(give_per( ) > 33)
          return true;
      else
          return false;
    }
    public Boolean iffirst( )
    {
        if(give_per( ) > 60)
            return true;
        else
            return false;
    }
    public Boolean iffail( )
    {
        if(give_per( ) < 33)
            return true;
        else return false;
    }
             
}

class disp
{
    public void dispf(res[ ] r)
    {
        System.out.print("\nRollNo\tName\tPer");
        for(int i = 0; i < 5; i++)
        {
                if(r[i].iffirst( )==true)
                    r[i].showinfo( );
        }
    }
 
    public void dispp(res[ ] r)
    {
        System.out.print("\nRollNo\tName\tPer");
        for(int i = 0; i < 5; i++)
        {
            if(r[i].ifpass( )==true)
                r[i].showinfo( );
        }
    }
     public void dispfl(res[ ] r)
    {
        System.out.print("\nRollNo\tName\tPer");
        for(int i = 0; i < 5; i++)
        {
            if(r[i].iffail( )==true)
                r[i].showinfo( );
        }
    }
}

public class Student
{
    public static void main(String[ ] args
    {
        res[] r = new res[5];
/*Here we have declared an array of the class res of size 5. The syntax for declaring arrays in java is 
 <return_type> [ ] <data_name> = new <return_type> [<size>]. The keyword new is used to allocate memory in the main memory for these new data items*/
        for(int i = 0; i < 5; i++)
            r[i] = new res( );
/*Now in order to use the objects in Java, you need to initialize them with constructors preceded by the keyword new. Now, what are constructors, we don't need to know that right now. But for this purpose, they are functions with the same name as that of the class, whose object is to be initialized*/ 
        disp d = new disp( );
        Scanner in = new Scanner(System.in);
        Boolean test = true;
        while(test == true)
        {
            System.out.print("\n****** Student Result Menu ******");
            System.out.print("\n\t 1. Enter Details");
            System.out.print("\n\t 2. Display First Division Holders");
            System.out.print("\n\t 3. Display Passed Students");
            System.out.print("\n\t 4. Display Failed Students");
            System.out.print("\n\t 5. Exit");
            System.out.print("\n\t Enter your choice :\t");
            int x = in.nextInt( );
            switch(x)
            {
                case 1:
                        for(int i = 0; i < 5; i++)
                        {
                            System.out.print("\n**** GETTING DETAILS :: STUDENT "+(i+1));
                            r[i].getinfo( );
                        }
                        break;
                case 2:
                        System.out.print("\n First Division Students \n\n");
                        d.dispf(r);
                        break;
                case 3:
                        System.out.print("\n Passed Students \n\n");
                        d.dispp(r);
                        break;
                case 4:
                        System.out.print("\n Failed Students \n\n");
                        d.dispfl(r);
                        break;
                case 5:
                        test = false;
                        break;
                default:
                        System.out.print("\nIvalid Entry");
            }
         
        }
    }
}

So folks, this is a completely executable code. You can copy paste it directly and compile and run it with JDK (Java Development Kit)  or using an IDE of your choice, say Netbeans.

Now if you want to know in more detail about what classes are, what are constructors. get into depths with return types, keywords, punctuators, literals etc. And in details about the concepts and laws that govern these programming language, then follow our series

"Insights into Programming"

Follow our facebook page for more updates:

Till now, we have been discussing codes in C/C++. Now. Let's move to Java. Here we have a simple beginners program in...

Posted by Code for School on Thursday, June 4, 2015

Wednesday, June 3, 2015

C++ Program to Find the Adjoint and Inverse of 3 X 3 Matrix

I developed this program in the second semester of my graduation. Initially, I searched for codes available on the internet and I found a few, but none of them produced the correct output, the implication being, the algorithms were flawed. Afterwards, I began developing an algorithm of my own, using of course the rudimentary knowledge of abstract mathematics, I learnt in high school. For calculating the Inverse and Adjoint of a matrix, the most important function, required is the one that calculates and returns the co-factors of individual elements in an array. Trying my hand at a few matrices, I discovered this interesting pattern that emerged.

The basic formula, that I find for co-factors was that if, in a function, say Give_Cof( ), that accepted two arguments int i and int j, the cofactor for that position is calculated as follows:

int cofactor =
A[(i+1)%3][(j+1)%3] * A[(i+2)%3][(j+2)%3] - A[(i+1)%3][(j+2)%3] * A[(i+2)%3][(j+1)%3];

I thought that the codes would work, but they generated erroneous results. for, I had not considered that co factors are different from minors in the sense that

Cofactor = (-1)^i+j * Minor.

I tried a different code, factoring the sign that was to be coalesced,

int cofactor =
(A[(i+1)%3][(j+1)%3] * A[(i+2)%3][(j+2)%3] - A[(i+1)%3][(j+2)%3] * A[(i+2)%3][(j+1)%3]) * pow(-1,(i+j));    //the function pow requires the header file math.h h to be included, in order to work

But even that didn't correct the function. After that, I tried applying that formula on different matrices, and the defect in the algorithm came to light. I observed that for odd positions, the formula fetched the Left hand operand after the right hand operand, which was creating the problem in the first place. Whereas, the code worked just fine for the elements at even positions i.e (i+j)%2 == 0.

The following function summarizes my findings:

int give_Cof(int A[][], int i, int j)    //A[][3] is a 3 X 3, two dimensional array, i, j denote the position
{                                                       // of the element                                         
         int cofactor;
         if((i + j)%2 == 0)
         {
                       cofactor = A[(m+1)%3][(n+1)%3] * A[(m+2)%3][(n+2)%3] -
                                         A[(m+1)%3][(n+2)%3] * A[(m+2)%3][(n+1)%3];
         }
         else
         {
                       cofactor = -(-A[(m+1)%3][(n+1)%3] * A[(m+2)%3][(n+2)%3] +
                                             A[(m+1)%3][(n+2)%3] * A[(m+2)%3][(n+1)%3]);
         }
         return cofactor;
}


The complete, executable program, follows;

#include <iostream>

using namespace std;

int min(int A[][3], int m, int n)
{
    int minor;
    if((m+n)%2 == 0)
    {
        minor = A[(m+1)%3][(n+1)%3] * A[(m+2)%3][(n+2)%3] -
                      A[(m+1)%3][(n+2)%3] * A[(m+2)%3][(n+1)%3];
    }
    else
    {
        minor = (-A[(m+1)%3][(n+1)%3] * A[(m+2)%3][(n+2)%3] +
                         A[(m+1)%3][(n+2)%3] * A[(m+2)%3][(n+1)%3]);       
    }
    return minor;
}

int give_Cof(int A[][3], int m, int n)
{
    int cofactor;
    if((m+n)%2 == 0)
    {
        cofactor = min(A,m,n);
    }
    else
    {
        cofactor = -min(A,m,n);     
    }
    return cofactor;
}

class Matrix
{
private:
    int A[3][3];
public:
    void getMatrix()
    {
        for(int i = 0; i < 3; i++)
        {
            cout<<"\nEnter the Elements of row "<<i+1<<"\t";
            for(int j = 0; j < 3; j++)
                cin>>A[i][j];
        }
    }
    void showMatrix()
    {
        for(int i = 0; i < 3; i++)
        {     
            cout<<endl;
            for(int j = 0; j < 3; j++)
                cout<<"\t"<<A[i][j];
        }     
    }
    int Determinant()
    {
        int x = A[0][0] * Cofactor(0,0);
        int y = A[0][1] * Cofactor(0,1);
        int z = A[0][2] * Cofactor(0,2);
        int det = x + y + z;
        return det;
    }
    int Minor(int m, int n)
    {
        int minor = min(A,m,n);
        return minor;
    }
    int Cofactor(int m, int n)
    {
        int cof = give_Cof(A,m,n);
        return cof;
    }
    void Transpose()
    {
        int Tran[3][3];
        for(int i = 0; i < 3; i++)
            for(int j = 0; j < 3; j++)
                Tran[i][j] = A[j][i];
        for(int i = 0; i < 3; i++)
        {
            cout<<endl;
            for(int j = 0; j < 3; j++)
                cout<<"\t"<<Tran[i][j];
        }
    }
    void Adj()
    {
        int Adjt[3][3], Adj[3][3];
        for(int i = 0; i < 3; i++)
            for(int j = 0; j < 3; j++)
                Adjt[i][j] = Cofactor(i,j);
        for(int i = 0; i < 3; i++)
        {
            cout<<endl;
            for(int j = 0; j < 3; j++)
            {
                Adj[i][j] = Adjt[j][i];
                cout<<"\t"<<Adj[i][j];
            }
        }
      
    }
    void Inverse()
    {
        int Adjt[3][3], Adj[3][3];
        float Inv[3][3];
        for(int i = 0; i < 3; i++)
            for(int j = 0; j < 3; j++)
                Adjt[i][j] = Cofactor(i,j);
        for(int i = 0; i < 3; i++)
        { 
            cout<<endl;
            for(int j = 0; j < 3; j++)
            {
                Adj[i][j] = Adjt[j][i];
                Inv[i][j] = Adj[i][j];
                Inv[i][j] = Inv[i][j]/Determinant();
                cout<<"\t"<<Inv[i][j];
            }
        }
    }
};

int main(int argc, char **argv)
{
    Matrix M;
    bool ch = true;
    while(ch == true)
    {
        cout<<"\n\n\n****** Matrix Operation Menu ******";
        cout<<"\n***********************************";
        cout<<"\n 1. Enter The Matrix ";
        cout<<"\n 2. Display The Matrix";
        cout<<"\n 3. Display the determinant of the Matrix";
        cout<<"\n 4. Display the Minors of the Matrix";
        cout<<"\n 5. Display the Cofactors of the Matrix";
        cout<<"\n 6. Display the Transpose of the Matrix";
        cout<<"\n 7. Display the Adjoint of the Matrix";
        cout<<"\n 8. Display the Inverse of the Matrix";
        cout<<"\n 9. Exit";
        cout<<"\nEnter your choice :\t";
        int x;
        cin>>x;
        SWITCH(x)
        {
            case 1:
                M.getMatrix();
                break;
            case 2:
                M.showMatrix();
                break;
            case 3:
                cout<<"\nThe Determinant of the Matrix is :\t"<<M.Determinant();
                break;
            case 4:
                cout<<"\nMinors of the Matrix are : ";
                for(int i = 0; i < 3; i++)
                {
                    cout<<endl;
                    for(int j = 0; j < 3; j++)
                        cout<<"\t"<<M.Minor(i,j);
                }
                break;
            case 5:
                cout<<"\nCofactors of the Matrix are : ";
                for(int i = 0; i < 3; i++)
                {
                    cout<<endl;
                    for(int j = 0; j < 3; j++)
                        cout<<"\t"<<M.Cofactor(i,j);
                }
                break;
            case 6:
                M.Transpose();
                break;
            case 7:
                M.Adj();
                break;
            case 8:
                M.Inverse();
                break;
            case 9:
                ch = false;
                break;
            default:
                cout<<"\nInvalid Entry!!!";   
        }
    }
    return 0;

}

A sample output might enhance the understanding of the program, and that's why , I have provide one, below:

****** Matrix Operation Menu ******
***********************************
 1. Enter The Matrix
 2. Display The Matrix
 3. Display the determinant of the Matrix
 4. Display the Minors of the Matrix
 5. Display the Cofactors of the Matrix
 6. Display the Transpose of the Matrix
 7. Display the Adjoint of the Matrix
 8. Display the Inverse of the Matrix
 9. Exit
Enter your choice :     1

Enter the Elements of row 1     1 3 3

Enter the Elements of row 2     1 4 3

Enter the Elements of row 3     1 3 4



****** Matrix Operation Menu ******
***********************************
 1. Enter The Matrix
 2. Display The Matrix
 3. Display the determinant of the Matrix
 4. Display the Minors of the Matrix
 5. Display the Cofactors of the Matrix
 6. Display the Transpose of the Matrix
 7. Display the Adjoint of the Matrix
 8. Display the Inverse of the Matrix
 9. Exit
Enter your choice :     2

        1       3       3
        1       4       3
        1       3       4


****** Matrix Operation Menu ******
***********************************
 1. Enter The Matrix
 2. Display The Matrix
 3. Display the determinant of the Matrix
 4. Display the Minors of the Matrix
 5. Display the Cofactors of the Matrix
 6. Display the Transpose of the Matrix
 7. Display the Adjoint of the Matrix
 8. Display the Inverse of the Matrix
 9. Exit
Enter your choice :     3

The Determinant of the Matrix is :      1


****** Matrix Operation Menu ******
***********************************
 1. Enter The Matrix
 2. Display The Matrix
 3. Display the determinant of the Matrix
 4. Display the Minors of the Matrix
 5. Display the Cofactors of the Matrix
 6. Display the Transpose of the Matrix
 7. Display the Adjoint of the Matrix
 8. Display the Inverse of the Matrix
 9. Exit
Enter your choice :     4

Minors of the Matrix are :
        7       1       -1
        3       1       0
        -3      0       1


****** Matrix Operation Menu ******
***********************************
 1. Enter The Matrix
 2. Display The Matrix
 3. Display the determinant of the Matrix
 4. Display the Minors of the Matrix
 5. Display the Cofactors of the Matrix
 6. Display the Transpose of the Matrix
 7. Display the Adjoint of the Matrix
 8. Display the Inverse of the Matrix
 9. Exit
Enter your choice :     5

Cofactors of the Matrix are :
        7       -1      -1
        -3      1       0
        -3      0       1


****** Matrix Operation Menu ******
***********************************
 1. Enter The Matrix
 2. Display The Matrix
 3. Display the determinant of the Matrix
 4. Display the Minors of the Matrix
 5. Display the Cofactors of the Matrix
 6. Display the Transpose of the Matrix
 7. Display the Adjoint of the Matrix
 8. Display the Inverse of the Matrix
 9. Exit
Enter your choice :     6

        1       1       1
        3       4       3
        3       3       4


****** Matrix Operation Menu ******
***********************************
 1. Enter The Matrix
 2. Display The Matrix
 3. Display the determinant of the Matrix
 4. Display the Minors of the Matrix
 5. Display the Cofactors of the Matrix
 6. Display the Transpose of the Matrix
 7. Display the Adjoint of the Matrix
 8. Display the Inverse of the Matrix
 9. Exit
Enter your choice :     7

        7       -3      -3
        -1      1       0
        -1      0       1


****** Matrix Operation Menu ******
***********************************
 1. Enter The Matrix
 2. Display The Matrix
 3. Display the determinant of the Matrix
 4. Display the Minors of the Matrix
 5. Display the Cofactors of the Matrix
 6. Display the Transpose of the Matrix
 7. Display the Adjoint of the Matrix
 8. Display the Inverse of the Matrix
 9. Exit
Enter your choice :     8

        7       -3      -3
        -1      1       0
        -1      0       1


****** Matrix Operation Menu ******
***********************************
 1. Enter The Matrix
 2. Display The Matrix
 3. Display the determinant of the Matrix
 4. Display the Minors of the Matrix
 5. Display the Cofactors of the Matrix
 6. Display the Transpose of the Matrix
 7. Display the Adjoint of the Matrix
 8. Display the Inverse of the Matrix
 9. Exit
Enter your choice :     9

RUN SUCCESSFUL (total time: 1m 44s)


I hope this helps....