Diagonal Matrix

View previous topic View next topic Go down

Diagonal Matrix

Post  Adarzh on Fri Jan 16, 2009 11:29 am

This program will calculate the sum of diagonal elements in a matrix

Code:

public class DiagonalMatrix
{
    public static void main(String[] args)
    {
        int val = 1;
        int[][] td = new int[6][6];
        for(int i = 0; i <5; i++)
        {
            for(int j=0; j <5; j++)
            {
                td[i][j] = val;
                val++;
            }
            val =2;
        }

        System.out.println("The Matrix Is :");
        for(int i = 0; i < 5; i++)
        {
            for(int j = 0; j <5; j++)
            {
                System.out.print(td[i][j]);
            }
            System.out.println();
        }

        int sum = 0;
        System.out.println("Diagonal Elements Are");
        for(int i = 0; i <5; i++)
        {
            for(int j=0; j <5; j++)
            {
                if(td[i] == td[j])
                {
                    System.out.print(td[i][j]);
                    sum = sum + td[i][j];
                }
            }
            System.out.println("");
        }
        System.out.println("Sum of diagonal elements = " + sum);
       
    }
}


Output

The Matrix Is :
12345
23456
23456
23456
23456
Diagonal Elements Are
1
3
4
5
6
Sum of diagonal elements = 19

Adarzh
Admin

Posts: 5
Join date: 2008-12-22

View user profile http://adarzh.youneed.us

Back to top Go down

Thanks

Post  Premarin on Sat Nov 07, 2009 2:44 pm

Thanks

Premarin

Posts: 1
Join date: 2009-11-07

View user profile

Back to top Go down

View previous topic View next topic Back to top


Permissions of this forum:
You cannot reply to topics in this forum