Friday, March 25, 2011

BlueJ program to print diagonal values from a 2d array


This program will print all the elements above the left diagonal and all elements below right diagonal of a 2d array.

How to proceed on this 2d array program

First of all for this program, the 2d array must be square means row and column must be same. Left diagonal of a 2d array means where both row number and column numbers are same. We have to print the values above left diagonal (excluding the values on the left diagonal of the 2d array). So print the values of the cell of the 2d array where row is less than the column.

Similarly right diagonal of a 2d array passes through the points where row number plus column number is equal to size-1, here size means either row or column size of the 2d array. So, by printing the values of the locations of the 2d array where row plus column is either greater than or equal to size of the 2d array.

Codes of the 2d array program.


import java.io.*;
class Dia
{
 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
 int arr[][];
 int i,j,m;
 public void takeValues() throws Exception
 {
  System.out.println("\nEnter the row number( It should be a square matrix):");
  m=Integer.parseInt(br.readLine());
  arr=new int[m][m];
  for(i=0; i< m;i++)
  {
   for(j=0; j< m;j++)
   {
   System.out.println("\nEnter Value:");
   arr[i][j]=Integer.parseInt(br.readLine());
   }
   }
   System.out.println("\nThe matrix is as follows:");
  for(i=0; i< m;i++)
  {
   for(j=0; j< m;j++)
   {
   System.out.print(" "+arr[i][j]);
   }
   System.out.println();
  }
  System.out.println("\nThe elements above left diagonal\n");
  for(i=0; i< m;i++)
  {
   for(j=0; j< m;j++)
   {
   if(i< j)
   System.out.print(" "+arr[i][j]);
   }
  }
  System.out.println();
  System.out.println("\nThe elements below the right diagonal\n");
  for(i=0; i< m;i++)
  {
   for(j=0;j< m;j++)
   {
   if(i+j >=m)
   System.out.print(" "+arr[i][j]);
   }
  }
  System.out.println();
 }
 public static void main(String args[]) throws Exception
 {
  Dia ob=new Dia();
  ob.takeValues();
  }
  }


No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner