12.1 Multi Dimensional Arrays

Saturday, August 22, 2009 Posted by Sudarsan
Variable-Length Arguments

By the help of Variable-Length arguments we can create methods that can accept an unspecified number of arguments. These are a new feature in J2SE 5.0

An argument type fallowed by an ellipsis (…) in a method’s argument list indicates that the method receives a variable number of arguments of the particular type.

The usage of ellipsis can occur only once in parameter list

Have a look at the fallowing example to know more about Variable-Length Arguments (vargs)

//Using VARGS

/**
 *
 * @author Sudarsan
 */
public class Main {

    // VARGS method is used to calculate total
    public static int total(int... nums)
    {
        int tot=0;
        
        for(int i:nums)
        {
            tot=tot+i;
        }
        
        return tot;
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        int x=10;
        int y=20;
        int z=30;

        System.out.printf("Sum of x+y+z : %d\n", total(x,y,z));
        System.out.printf("Sum of x+y   : %d\n", total(x,y));
        System.out.printf("Sum of x+z   : %d\n", total(x,z));

    }

}
When we compile this we can get the fallowing output
Sum of x+y+z : 60
Sum of x+y : 30
Sum of x+z : 40

Multi Dimensional Arrays

Multi dimensional arrays with two dimensions are often used to represent tables of values consisting of information arranged in rows and columns.

Arrays that require two indices to identify a particular element are called two-dimensional arrays.

An array with p rows and q columns is called a p-by-q array.

A two dimensional array can be initialized with an array initilizer of the form

datatype variable[][]={ {row 1},{row 2}, ……};

Multidimensional arrays are maintained as arrays of separate one-dimensional arrays. As a result, the lengths of the rows in a two-dimensional array are not required to be the same.

A multidimensional array with the same number of columns in every row can be created with an array-creation expression of the form

 datatype variable[]=new datatype[rows][columns];

For example, the following declares a two-dimensional array variable called nums

int nums[][] = new int[4][5];

This allocates a 4 by 5 array and assigns it tonums internally this matrix is implemented as an array of arrays of int.

Have a look at the fallowing examples to know more about 2D Arrays

Assigning Values at Design Time to a 2D Array

// Initilizing Two dimensional Array

/**
 *
 * @author Sudarsan
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        int a[][]={{10,20,30},{40,50,60}};
        int b[][]={{10,20},{30},{40,50,60}};

        System.out.println("Values in Array A are ....");

        for(int i=0;i<a.length;i++)
        {
            for(int j=0;j<a[i].length;j++)
            {
                System.out.printf("%d ",a[i][j]);
            }

            System.out.println();
        }

        System.out.println("Values in Array B are .....");

        for(int i=0;i<b.length;i++)
        {
            for(int j=0;j<b[i].length;j++)
            {
                System.out.printf("%d ",b[i][j]);
            }
            System.out.println();
        }

    }

}

The output of the above program is given below

Values in Array A are ....
10 20 30
40 50 60
Values in Array B are .....
10 20
30
40 50 60

Assigning Values to 2D Array at Run Time

// Reading values into 2D Array at Runtime

import java.util.Scanner;

/**
 *
 * @author Sudarsan
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        int a[][];
        a=new int[2][2];

        Scanner s=new Scanner(System.in);

        System.out.println("Enter Values into 2D Array ...");

        for(int i=0;i<a.length;i++)
        {
            for(int j=0;j<a[i].length;j++)
            {
                a[i][j]=s.nextInt();

            }
        }

        System.out.println("The Values in the Array are....");

        for(int i=0;i<a.length;i++)
        {
            for(int j=0;j<a[i].length;j++)
            {
                System.out.printf("%d\t",a[i][j]);
            }

            System.out.println();
        }


    }

}

The output of the above program is given below

Enter Values into 2D Array ...
10
20
30
40
The Values in the Array are....
10 20
30 40

Passing 2D Array as a parameter to a Constructor

//Student.java

package d3;

/**
 *
 * @author Sudarsan
 */
public class Student {

    private int marks[][];

    //passing 2d array to a constructor
    
    public Student(int m[][])
    {
        marks=m;
    }

    public void stats()
    {
        System.out.printf("Minimum Marks : %d\n", min());
        System.out.printf("Maximum Marks : %d\n", max());
    }

    public int min()
    {
        int low=marks[0][0];

        for(int smarks[]:marks)
        {
           for(int mark : smarks)
           {
               if(mark<low)
                   low=mark;
           }
        }

        return low;
    }

    public int max()
    {
        int high=marks[0][0];

        for(int smarks[]:marks)
        {
            for(int mark:smarks)
            {
                if(mark>high)
                    high=mark;
            }
        }

        return high;
    }

    public int totalMarks(int groupMark[])
    {
        int tot=0;

        for(int mark: groupMark)
            tot+=mark;

        return tot;
    }

    public void outputResult()
    {
        System.out.println("The Student Report:");
        System.out.print("         ");

        for(int i=0;i<marks[0].length;i++)
            System.out.printf("Subject %d", i+1);

        System.out.println("Total");

        for(int j=0;j<marks.length;j++)
        {
            System.out.printf("Student %2d", j+1);

            for(int i:marks[j])
                System.out.printf("%8d", i);

            int tot=totalMarks(marks[j]);
            System.out.printf("%9d\n", tot);
        }
    }
}

//Constructiong Student Object

import java.util.Scanner;
/**
 *
 * @author Sudarsan
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        int m[][];
        m=new int[3][3];

        Scanner s=new Scanner(System.in);

        System.out.println("Enter Five Student Marks for Three Subjects :");

        for(int i=0;i<m.length;i++)
        {
            System.out.printf("Student %d\n", i+1);
            for(int j=0;j<m[i].length;j++)
            {
                System.out.printf("Subject %d : ", j+1);
                m[i][j]=s.nextInt();
            }
        }

        // passing 2d array as a parameter
        
        Student std=new Student(m);
        std.outputResult();
        std.stats();
    }

}

When we compile this program we can see the fallowing output

Enter Five Student Marks for Three Subjects :
Student 1
Subject 1 :
41
Subject 2 :
25
Subject 3 :
98
Student 2
Subject 1 :
14
Subject 2 :
65
Subject 3 :
33
Student 3
Subject 1 :
78
Subject 2 :
58
Subject 3 :
88
The Student Report:
Subject 1Subject 2Subject 3Total
Student 1 41 25 98 164
Student 2 14 65 33 112
Student 3 78 58 88 224
Minimum Marks : 14
Maximum Marks : 98
Labels:

Post a Comment