Monday, August 19, 2019

Two Dimensional Numeric Array Program With Diagonal Values


BlueJ program on two dimensional numeric array diagonal values.

Write a program in Java to compute the (a) product of all elements below the main diagonal and (b) sum of all elements above the main diagonal of a matrix of 4 X 4

The Major Diagonal Elements are the ones that occur from Top Left of Matrix Down To Bottom Right Corner. The Major Diagonal is also known as Main Diagonal or Primary Diagonal.

0,0




1,1




2,2




3,3

When row no is greater than column no, it is below main diagonal and above main diagonal means row number is less than column number

import java.util.*;
class Diagonal
{
Scanner sc=new Scanner(System.in);
int arr[][]=new int [4][4];
int product,sum,i,j;
public void takeDatas()
{
   for(i=0;i<=3;i++)
   {
        for(j=0;j<=3;j++)
        {
             System.out.print("\nEnter Value:");
             arr[i][j]=sc.nextInt();
            }
        }
        System.out.println("\nArray as follows");
        for(i=0;i<=3;i++)
   {
        for(j=0;j<=3;j++)
        {
             System.out.print(arr[i][j]+ " ");
        }
        System.out.println();
    }
    show();
    }

 public void show()
 {
      product=1;
      sum=0;
      for(i=0;i<=3;i++)
   {
        for(j=0;j<=3;j++)
        {
            if(i >j)
            product=product*arr[i][j];
            else if(i< j)
            sum=sum+arr[i][j];
        }
    }
    System.out.print("\nProduct of all elements below the main diagonal :"+ product);
    System.out.print("\nSum of all elements above the main diagonal :"+ sum);     
  }
     
public static void main(String args[])throws Exception
{
Diagonal ob=new Diagonal ();
ob.takeDatas();
}
}

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner